Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org

Related items

Math functions in JavaScript

Selecting Random Numbers

Nested Splitting

Split Ends

Random Numbers & Random Events

Scrolling Text

How long is a piece of string?

You are here: irt.org | Articles | JavaScript | Text, String, and Number | How long is a piece of string? [ previous next ]

Published on: Saturday 30th August 1997 By: Martin Webb

Introduction

This article will describe some of the methods associated with the String object, and how to use them to find characters or strings within strings, to replace characters and portions of text, to change the case, and to alter the style and formatting of text.

Properties and methods

The main String property is length which returns the length of the string:

<SCRIPT LANGUAGE="JavaScript"><!--
var text = '0123456789';
document.write('Length of "' + text + '" is ' + text.length);
//--></SCRIPT>

Which when run produces:

The String object has many methods associated with it.

In the following, assume that text contains "abcxyzXYZxyz":

Find and Replace

We can use the indexOf method to find and replace items within a string.

The following replace() function, takes three parameters, text the character or string to be replaced, by the character or string to replace it with and string which is to be modified.

The first thing it does is test the length of string and text, and if one or the other is zero it retuns the current string.

The variable i then holds the index of the first occurrence of text within the string using the indexOf() method.

If i is null, i.e. !i meaning not found for JavaScript 1, and text is not located at the start of the string then it again returns the current string. This complicated check is required as !i is equivalent to a value of 0, and as 0 is a valid index, it is neccessary to double check before rejecting it.

It then tests i for -1, which since JavaScript 1.1 also means not found, and again returns the current string.

It then starts to create a newstr string based on the contents of the string upto the the i index, plus the replacement by string.

A check is then made to see if the length of the text to be replaced is less than the length of the current string, if it is then it reiterates the replace() function, using the remainder of the current string.

The last thing it does is to return the newstr string.

<SCRIPT LANGUAGE="JavaScript"><!--
function replace(string,text,by) {
// Replaces text with by in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}

document.write(replace('XXXX','X','Y') + '<BR>');
document.write(replace('TXTXTXTX','TX','TY') + '<BR>');
document.write(replace('TXTXTXTX','TX','Y') + '<BR>');
document.write(replace('X','Y','Z') + '<BR>');
document.write(replace('','X','Y') + '<BR>');
document.write(replace(' X','X','Y') + '<BR>');
document.write(replace('X ','X','Y') + '<BR>');
//--></SCRIPT>

Which when run produces something like the following:

I've mentioned the phrase 'current string' quite a few times. The reason being, that because the replace() function is interated until there are no more occurences of the text string within the string, then the string passed is constantly changing through each iteration.

For example when replacing the character 'o' within 'Six of one and half a dozen of the other' the different current strings through the iterations are:

One potential use of the replace() function is to highlight a particular phrase, for example:

<SCRIPT LANGUAGE="JavaScript"><!--
document.write(replace('oOoOoOoOoOoOoOo','o','<FONT COLOR="#FF0000">o<\/FONT>'));
//--></SCRIPT>

Another is to remove items from a string:

<SCRIPT LANGUAGE="JavaScript"><!--
document.write(replace('oOoOoOoOoOoOoOo','o',''));
//--></SCRIPT>

UPPER and lower CaSe

There are two String object methods toLowerCase() and toUpperCase() which change the case of the string.

The following example reuses the replace() function to convert the first character of the text string within the string to upper case using the toUpperCase() method.

The upperFirst() function uses the charAt(0) method to locate the first character of text string which is changed to upper case and then appends it with the remainder of the text string using the substring() method.

<SCRIPT LANGUAGE="JavaScript"><!--
function upperFirst(string,text) {
    return replace(string,text,text.charAt(0).toUpperCase() + text.substring(1,text.length));
}

document.write(upperFirst('javascript is not java','java'));
//--></SCRIPT>

Which when run produces:

This example can be extended by placing the output of the upperFirst() function as the input to yet another upperFirst() function, for example:

<SCRIPT LANGUAGE="JavaScript"><!--
document.write(upperFirst(upperFirst('javascript is not java','java'),'script'));
//--></SCRIPT>

Which when run produces:

Rather than pass the output of one function into the input of another it is possible to pass the parameters all in one go to an intermediate function. In the following example the multipleUpperIntial() function accepts the first parameter string and then processes all the remaining arguments using the length property of the arguments, each one in term is passed to the upperInitial() function.

<SCRIPT LANGUAGE="JavaScript"><!--
function upperInitial(string,text) {
    return replace(string,' '+text,' '+text.charAt(0).toUpperCase() + text.substring(1,text.length));
}

function multipleUpperInitial(string) {
    for (var i = 1; i < multipleUpperInitial.arguments.length; i++)
        string = upperInitial(string,multipleUpperInitial.arguments[i]);
    return string;
}

document.write(multipleUpperInitial('The quick brown fox jumps over the lazy dog','q','b','f','j','o','t','l','d'));
//--></SCRIPT>

Which when run produces the following:

Style and Presentation

There are 11 String object methods that effect the style of text. For example to make text bold:

<SCRIPT LANGUAGE="JavaScript"><!--
var text = 'This is bold';
document.write(text.bold() + '<BR>');

// or

document.write('This is also bold'.bold() + '<BR>');
//--></SCRIPT>

Which when run produces the following:

The following diplays the complete range available:

<SCRIPT LANGUAGE="JavaScript"><!--
document.write('big'.big()            + ' ');
document.write('blink'.blink()        + ' ');
document.write('bold'.bold()          + ' ');
document.write('italics'.italics()    + ' ');
document.write('small'.small()        + ' ');
document.write('strike'.strike()      + ' ');
document.write('sub'.sub()            + ' ');
document.write('sup'.sup()            + ' ');
document.write('fixed'.fixed()        + ' ');
document.write('fontsize'.fontsize(5) + ' ');
document.write('fontcolor'.fontcolor('maroon'));
//--></SCRIPT>

Which produces:

Even silly special effects can be produced. For example, to produce the following using HTML would require 37 sets of <FONT SIZE=i>x</FONT>:

Whereas it uses a simple scale() function to accept a string which is then altered a character at a time using the fontsize() method.

<SCRIPT LANGUAGE="JavaScript"><!--
function scale(string) {
    var j = 1;
    var inc = 1;
    var newstr = '';
    for (var i=0; i< string.length; i++) {
        var ch = string.charAt(i);
        newstr = newstr + ch.fontsize(j);
        j = j + inc;
        if (j == 8) { j=6;inc=-1 }
        if (j == 0) { j=2;inc=1 }
    }
    return newstr;
}

document.write(scale('ooooooooooooooooooooooooooooooooooooo'));
//--></SCRIPT>

Once the scale() function has been defined it can be used again and again:

<SCRIPT LANGUAGE="JavaScript"><!--
document.write(scale('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')+'<P>');
document.write(scale('ooooooooooooooooooooooooooooooooooooo'));
//--></SCRIPT>

The following example demonstrates what the methods are doing. If you select any of the checkboxes you will see that the text is wrapped with the appropriate HTML commands required to change the style of the text. For example, if you select bold, the the testForm will show the value of the string as <B>text</B>. Which is why, if you were to write the value of the string to the document using document.write() the string would render as bold.


bold: italics: big:
blink: small: strike:
sub: sup: fixed:
fontcolor: fontsize:

The String Section

You can easily create a string library (stringLib.js) containing all your string functions that you create, for example:

function replace(string,text,by) {
// Replaces text with by in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}


function upperFirst(string,text) {
    return replace(string,text,text.charAt(0).toUpperCase() + text.substring(1,text.length));
}

function upperInitial(string,text) {
    return replace(string,' '+text,' '+text.charAt(0).toUpperCase() + text.substring(1,text.length));
}

function upperInitial(string,text) {
    return replace(string,' '+text,' '+text.charAt(0).toUpperCase() + text.substring(1,text.length));
}

function multipleUpperInitial(string) {
    for (var i = 1; i < multipleUpperInitial.arguments.length; i++)
        string = upperInitial(string,multipleUpperInitial.arguments[i]);
    return string;
}

Notice that there is no HTML whatsoever in the file - THIS IS IMPORTANT!

Then all your string functions are available to any and all your documents with the inclusion of one line:

<SCRIPT SRC="stringLib.js">
</SCRIPT>

Alright then - two lines.

For more information on JavaScript *.js source files look at Source Files.

Related items

Math functions in JavaScript

Selecting Random Numbers

Nested Splitting

Split Ends

Random Numbers & Random Events

Scrolling Text

©2018 Martin Webb