Section F. Working with strings


F. Working with strings

Strings are JavaScript's most versatile data type, and you'll manipulate them often.

Quotes

A literal string is always surrounded by quotes. This alerts JavaScript to the fact that it's a string:

var exampleString = 'I am a JavaScript hacker'; var exampleString2 = '49'; 


As we already saw, the quotes make the second example a string, too, even though it happens to contain only numerical characters.

JavaScript also allows you to use double quotes. So this, too, is perfectly valid JavaScript:

var exampleString = "I am a JavaScript hacker"; var exampleString2 = "49"; 


Choosing between Single and Double Quotes

Long ago I decided that I'd always use single quotes for JavaScript and double quotes for HTML, even though both languages allow both types of marks. Therefore I nearly always use single quotes to delimit JavaScript strings.

I advise you to make such a rule for yourself, since it'll make your code more readable and will occasionally prevent errors.


But what if a string contains quotation marks? What if I need the string 'I'm a JavaScript hacker'? This doesn't work:

   var exampleString = 'I'm a JavaScript hacker'; 


JavaScript sees the second quotethe one being used as an apostropheas a string delimiter. Therefore it reads the string 'I', followed by a bunch of variable names it doesn't understand. The result is an error message.

One solution is to use double quotes as string delimiters:

var exampleString = "I'm a JavaScript hacker"; 


JavaScript sees that you're using double quotes to delimit the string, and therefore considers the single quote a part of the string.

The other solution is to escape the single quote. This is done by adding a backslash (\) just before the character. This backslash tells JavaScript to treat the next character as a character, not as a string delimiter. So this, too, is a valid way of defining the string:

var exampleString = 'I\'m a JavaScript hacker'; 


Now JavaScript treats the second quote as a part of the string.

Concatenation: +

As you learned in 5B, string concatenation means "sewing strings together." The principle is simple:

var exampleString = 'I am a JavaScript hacker'; var exampleString2 = 'Hello world'; alert(exampleString2 + exampleString); 


This yields "Hello worldI am a JavaScript hacker". You might want a space between the two sentences. No problem:

alert(exampleString2 + ' ' + exampleString); 


The shorthand notation also works fine:

exampleString2 += ' ' + exampleString; 


Unfortunately, string concatenation uses the same + operator as does mathematical addition (as we saw in 5B).

The String object

As soon as you create a string it's made into a String object, which contains a few useful methods and properties that allow you to quickly and easily manipulate the string. They are among the most important tools of every JavaScript programmer.

length

A string has a length, and the length property allows you to determine it:

var exampleString = 'I am a JavaScript hacker'; alert(exampleString.length); // yields 24 


Note that this is a read-only property.

indexOf() and lastIndexOf()

By far the most notorious String method is indexOf(). It returns the index number of a string within the main string, and is often used in browser detects (see 3D) to determine whether the user-agent string of a browser contains, for instance, 'MSIE'. Note that the first character in a string has index number 0, not 1.

For example:

var exampleString = 'I am a JavaScript hacker'; alert(exampleString.indexOf('JavaScript')); // yields 7 


This yields 7, since the substring 'JavaScript' starts at the eighth character (index number 7) in exampleString.

If the requested string does not exist, indexOf() returns -1:

var exampleString = 'I am a JavaScript hacker'; alert(exampleString.indexOf('PHP')); // yields -1 


Now let's look at a slightly more complex example:

var exampleString = 'I am a JavaScript hacker'; alert(exampleString.indexOf('a')); // yields 2 


In fact, there are five 'a's in exampleString. Without further instructions, indexOf() always returns the index number of the first character that matches the substring. Therefore, the previous example will yield 2 (which is the index number of the third character).

But suppose you want to look for the second 'a' in the string. You have to give indexOf() extra instructions by adding an argument:

var exampleString = 'I am a JavaScript hacker'; alert(exampleString.indexOf('a',3)); // yields 5 


Now indexOf() starts its search at the fourth character (with index number 3) and returns 5, since the first 'a' after the fourth character is the sixth character (with index number 5) in the string.

More generally, the following code always returns the position of the second 'a' in any string:

var secondA = exampleString.indexOf('a', exampleString.indexOf('a')+1); 


The lastIndexOf() method works the same as indexOf(), except that it searches backwards from the end of the string:

var exampleString = 'I am a JavaScript hacker'; alert(exampleString.lastIndexOf('a')); // yields 19 


Here, too, you can define a second argument that says where the search should start:

var exampleString = 'I am a JavaScript hacker'; alert(exampleString.lastIndexOf('a'),18); // yields 10 


charAt()

The charAt() method allows you to find a character at a certain position in the string:

var exampleString = 'I am a JavaScript hacker'; alert(exampleString.charAt(9)); // yields 'v' 


The tenth character in the string (with index number 9) is a 'v', so that's what the alert shows.

Example with Length, Indexof(), and Charat()

I occasionally use a combination of indexOf() and charAt() to find out if a user enters valid input. (Yes, I could also use a regular expression, but I'm bad at them and avoid them whenever possible.) Suppose the user is only allowed to enter vowels in a form field and I have to check each character to see if it's a vowel. I do that as follows:

var vowels = 'aeiouy'; var inputString = [read out form field]; for (var i=0;i<inputString.length;i++) {   if (vowels.indexOf(inputString.charAt(i)) == -1)          // notify user of error } 


The definition string vowels contains all the vowels. The script goes through the string the user has entered (inputString) character by character (i goes from 0 to the length of the string). It takes the character at each position (inputString.charAt(i)) and tries to find its position in the definition string vowels (vowels.indexOf(...)). If the character doesn't occur in the test string (indexOf(...) == -1), the user has entered a disallowed character.


substring()

The substring() method allows you to take a substring from a string. Of course, you have to specify the start and end point of the substring:

var exampleString = 'I am a JavaScript hacker'; alert(exampleString.substring(5,8)); 


The start character (index 5) is part of the substring, but the end character (index 8) is not. The sixth character (with index 5) is an 'a', and the eighth character (with index 7) is a 'J'. Therefore, this yields the string 'a J'.

You can also leave out the second argument, in which case the substring continues until the end of the string:

var exampleString = 'I am a JavaScript hacker'; alert(exampleString.substring(5)); 


Now the alert says 'a JavaScript hacker'.

split()

The split() method allows you to split a string into several parts. The argument of the function defines the character(s) the string should be split on, and split() returns an array. For instance:

var exampleString = 'I am a JavaScript hacker'; var splitString = exampleString.split('c'); 


Now exampleString is split wherever a 'c' occurs. All parts of the string become a new string, and splitString becomes an array that contains all these strings. (We'll discuss arrays in 5L.) The 'c' characters themselves are removed entirely.

So splitString becomes this array:

['I am a JavaS','ript ha','ker']; 


An excellent example of how to use split() is contained in Form Validation. This script allows the Web developer to define a custom validation attribute on form fields that tell the script which checks it should run on the form field. For instance:

<input name="phone" validation="required numeric" /> 


The validation script does this for all form fields:

[Form Validation, lines 80-98, condensed heavily]

// els[i] is the form field currently being investigated var req = els[i].getAttribute('validation'); var reqs = req.split(' '); for (var j=0;j<reqs.length;j++) {     // run check } 


It takes the validation attribute of the field. Then it splits this string by spaces and stores these strings in the array reqs. In the case of the example form field, reqs holds two strings: 'required' and 'numeric'. Now the script goes through these strings (the for loop) and performs the checks 'required' and 'numeric'.

toLowerCase() and toUpperCase()

The methods toLowerCase() and toUpperCase() make a string wholly lowercase or wholly uppercase:

var exampleString = 'I am a JavaScript hacker'; alert(exampleString.toLowerCase()); alert(exampleString.toUpperCase()); 


These alerts give 'i am a javascript hacker' and 'I AM A JAVASCRIPT HACKER', respectively.

These methods are occasionally useful when you compare strings. For instance, when you request the selectorText of a style rule (see 9D), some browsers return a lowercase string and others an uppercase string.

In Edit Style Sheet, I have to compare the returned selectorText with a string the user has chosen. Since I'm not certain whether either selectorText or the user string will be upper- or lowercase, I play it safe and convert both strings to lowercase before comparing them:

[Edit Style Sheet, line 52]

if (sheetRules[i].selectorText.toLowerCase() == selector.toLowerCase()) 


Of course, converting both to uppercase would work fine, too.



ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ISBN: N/A
EAN: N/A
Year: 2005
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net