Working with Strings

This handy reference covers strings and the String object in JavaScript. Each property and method of the String object is explained, along with examples.

In this reference article we'll explain what strings are, why they're important, and how they work in JavaScript. We'll cover all the properties and methods of strings, along with some simple examples.

What is a string?

A string is simply a number of characters (letters, numbers, spaces and so on) joined together. For example, the following are all strings:


Hello
abc123
Wow!!!
A string with many words
*$^&#~?!?!!!!

Creating strings

Creating a string variable in JavaScript is simple:


var myString = "This is mic number one";

Make sure you put the quotes around your string. You can use either double quotes (") or single quotes ('), but make sure you use the same type of quote at the beginning and at the end!

The String object

JavaScript can actually store strings in two ways: as a primitive string data type (this is what we created above), and as a String object. Here's how we'd create the same string as an object:


var myString = new String ( "This is mic number one" );

Although JavaScript can store strings as primitive data types or objects, you rarely have to worry about this distinction. JavaScript will automatically convert a string data type to a String object when it needs to, and vice-versa. As you'll see later on, we can happily use methods of the String object on primitive strings, and JavaScript won't bat an eyelid.

Basic string operations

You can compare two strings to see if they're equal, just as with number variables:


var stringOne = "This is mic number one";
var stringTwo = "Isn't this a lot of fun";

if ( stringOne == stringTwo ) alert ( "Strings match" );
if ( stringOne != stringTwo ) alert ( "Strings don't match" );

This of course pops up an alert saying "Strings don't match".

You can also join strings together using the + (concatenation) operator:


var stringOne = "This is mic number one";
var stringTwo = "Isn't this a lot of fun";

var stringThree = stringOne + ". " + stringOne + ". " + stringTwo + "!";
alert ( stringThree );

This pops up an alert saying "This is mic number one. This is mic number one. Isn't this a lot of fun!"

String properties

Strings in JavaScript only have one property that you need for everyday use: the length property. This tells you how long the string is, in characters:


var myString = "These go to eleven."
alert ( myString.length );

This pops up an alert saying "19".

String methods

There are many things you can do with strings in JavaScript. Usually you do these things with the methods of the String object. Let's take a look at each of these methods in alphabetical order.

To view the details of a method, click its Show details link. ( Show all | Hide all )

anchor()

stringObject.anchor ( anchorName )

This method lets you create an HTML anchor element in JavaScript. First you create a string to use for the anchor text, then use the anchor() method to create the anchor around that string:


myString = "(Listen to the) Flower People";
document.write ( myString.anchor("flowerPeople") );

The above code has the same effect as the following HTML:


<a name="flowerPeople">(Listen to the) Flower People</a>

big()

stringObject.big ( )

Returns the string formatted using a big font - it's the equivalent of the HTML <big></big> element:


myString = "Their appeal is becoming more selective.";
document.write ( myString.big() );

The above code has the same effect as the following HTML:


<big>Their appeal is becoming more selective.</big>

blink()

stringObject.blink ( )

bold()

stringObject.bold ( )

Returns the string formatted in bold text - it's the equivalent of the HTML <b></b> element:


myString = "Their appeal is becoming more selective.";
document.write ( myString.bold() );

The above code has the same effect as the following HTML:


<b>Their appeal is becoming more selective.</b>

charAt()

stringObject.charAt ( index )

Returns the character at position index in the string. String indices start from zero, so the first position is 0 and the last is stringObject.length - 1.


myString = "I believe virtually everything I read";
alert ( myString.charAt(7) );

This brings up an alert box displaying the letter 'v'.

charCodeAt()

stringObject.charCodeAt ( index )

Returns the Unicode value of the character at position index in the string. String indices start from zero, so the first position is 0 and the last is stringObject.length - 1.


myString = "I believe virtually everything I read";
alert ( myString.charAt(7) );

This brings up an alert box displaying the number 118 (the Unicode value for the letter 'v').

concat()

stringObject.concat ( string1, string2, ... stringN )

Concatenates strings together, much like the + string concatenation operator described above. Adds one or more strings onto the end of the string, and returns the resulting concatenated string:


stringOne = "It's such a fine line between stupid and";
stringTwo = "clever.";
alert ( stringOne.concat ( "... ", stringTwo ) );

This brings up an alert box displaying "It's such a fine line between stupid and... clever."

fixed()

stringObject.fixed ( )

Returns the string formatted using fixed-width (typewriter text) characters - it's the equivalent of the HTML <tt></tt> element:


myString = "Their appeal is becoming more selective.";
document.write ( myString.fixed() );

The above code has the same effect as the following HTML:


<tt>Their appeal is becoming more selective.</tt>

fontcolor()

stringObject.fontcolor ( color )

Returns the string formatted using the supplied foreground colour - it's the equivalent of the HTML <font color="..."></font> element:


myString = "Their appeal is becoming more selective.";
document.write ( myString.fontcolor("yellow") );

The above code has the same effect as the following HTML:


<font color="yellow">Their appeal is becoming more selective.</font>

The font element is deprecated in HTML 4, and should not be used. Therefore it's best to avoid using the fontcolor() method too.

fontsize()

stringObject.fontsize ( size )

Returns the string formatted using the supplied font size - it's the equivalent of the HTML <font size="..."></font> element:


myString = "Their appeal is becoming more selective.";
document.write ( myString.fontsize(5) );

The above code has the same effect as the following HTML:


<font size="5">Their appeal is becoming more selective.</font>

The font element is deprecated in HTML 4, and should not be used. Therefore it's best to avoid using the fontsize() method too.

fromCharCode()

String.fromCharCode ( code1, code2, ... codeN )

Returns a string of characters corresponding to the supplied character codes. This is a static method, which means it doesn't operate on a specific string object. You always call it using String.fromCharCode().


alert ( String.fromCharCode(84, 97, 112) );

This brings up an alert box displaying the word 'Tap'.

indexOf()

stringObject.indexOf ( searchText [, index] )

Searches the string stringObject for the first occurrence of searchText, optionally starting from index. String indices start from zero, so the first position is 0 and the last is stringObject.length - 1.

If searchText is found, indexOf() returns the index of the first character of the occurrence of searchText in stringObject. If searchText isn't found, indexOf() returns -1.

The search is case-sensitive.

For example:


myString = "...and the answer is, 'none, none... more black.'";
alert ( myString.indexOf("none") );      // Displays '23'
alert ( myString.indexOf("none", 24) );  // Displays '29'
alert ( myString.indexOf("None") );      // Displays '-1'

italics()

stringObject.italics ( )

Returns the string formatted in italic text - it's the equivalent of the HTML <i></i> element:


myString = "Their appeal is becoming more selective.";
document.write ( myString.italics() );

The above code has the same effect as the following HTML:


<i>Their appeal is becoming more selective.</i>

lastIndexOf()

stringObject.lastIndexOf ( searchText [, index] )

Searches the string stringObject backwards for the last occurrence of searchText, optionally starting from index. String indices start from zero, so the first position is 0 and the last is stringObject.length - 1.

If searchText is found, lastIndexOf() returns the index of the first character of the occurrence of searchText in stringObject. If searchText isn't found, lastIndexOf() returns -1.

The search is case-sensitive.

For example:


myString = "...and the answer is, 'none, none... more black.'";
alert ( myString.lastIndexOf("none") );      // Displays '29'
alert ( myString.lastIndexOf("none", 28) );  // Displays '23'
alert ( myString.lastIndexOf("None") );      // Displays '-1'

link()

stringObject.link ( targetURL )

match()

stringObject.match ( expression )

Attempts to match the regular expression expression against the text in stringObject. Unlike indexOf(), match() returns an array of strings that matched (if any), rather than a numeric index value. It also can use a regular expression for the search text. (We'll cover regular expressions in detail in a later tutorial.)

You can use the g regular expression modifier to return all matches (if omitted then only the first match is returned), and the m modifier to make the search work over multiple lines of text. You can also use the i modifier to make the search case-insensitive (if omitted then the search is case-sensitive).

For example:


myString = "...and the answer is, 'none, none... more black.'";
alert ( myString.match(/none/) );   // Displays 'none'
alert ( myString.match(/none/g) );  // Displays 'none,none' (2 matches)
alert ( myString.match(/None/) );   // Displays 'null'
alert ( myString.match(/None/i) );  // Displays 'none'

If you use the g regular expression modifier, the returned array simply contains a list of the matched strings.

If you don't use the g regular expression modifier — i.e. only 1 match is returned — the returned array contains the following elements and properties:

input
The string against which the regular expression was matched.
index
The index in the string at which the match was found.
[0]
The first element of the array, [0], contains the matched characters in the string.
[1], ...[n]
The remaining elements of the array contain the results of any substring matches created by using parentheses ( ( .. ) ) in the regular expression.

For example:


var lyrics = "My old man's a dustman, He wears a dustman's hat";
var matchResults = lyrics.match ( /dust(.*?),/ );
alert ( matchResults.input ); // Displays "My old man's a dustman, He wears a dustman's hat"
alert ( matchResults.index ); // Displays "15"
alert ( matchResults[0] );    // Displays "dustman,"
alert ( matchResults[1] );    // Displays "man"

If the regular expression doesn't match, null is returned, rather than an array. Therefore, make sure you check that a match occurred before trying to access the array, or you'll get an error. For example, if ( matchResults ) { (access the array here) }.

replace()

stringObject.replace ( expression [, replacementText|function] )

Attempts to match the regular expression expression against the text in stringObject. If the expression matches, it is replaced with the second argument, which can be a text string or the return value of a function. replace() returns the modified string.

You can use the g regular expression modifier to replace all matches (if omitted then only the first match is replaced), and the m modifier to make the search and replace work over multiple lines of text. You can also use the i modifier to make the search case-insensitive (if omitted then the search is case-sensitive).

Replacement with a text string

Here's a simple example of replacement with a text string:


myString = "No bones!";
alert ( myString.replace(/o/, "O") );  // Displays 'NO bones!'
alert ( myString.replace(/o/g, "O") ); // Displays 'NO bOnes!'

You can also use certain special variables in the replacement text, as follows:

  • $1, $2, ... $9: These contain any substrings from the original string that matched parts of the regular expression in parentheses.

For example, the following code:


myString = "Jazz Odyssey";
alert ( myString.replace(/(Jazz) (Odyssey)/, "An $2 in $1") );

...displays an alert saying, "An Odyssey in Jazz".

  • $& (lastMatch): This returns the last substring that was matched by the regular expression.

For example, the following code:


myString = "jazz exploration";
alert ( myString.replace(/jazz/, "A free-form $&") );

...displays an alert saying, "A free-form jazz exploration".

  • $+ (lastParen): This returns the last substring that was matched by a part of the regular expression in parentheses.

For example, the following code:


myString = "We hope you enjoy our new direction";
alert ( myString.replace(/We (hope)/, "$+") );

...displays an alert saying, "hope you enjoy our new direction".

  • $` (leftContext): This returns everything in the original string up to (but not including) the most recently matched character.

For example, the following code:


myString = "Hello, Cleveland!";
alert ( myString.replace(/ /, " $` ") );

...displays an alert saying, "Hello, Hello, Cleveland!".

  • $' (rightContext): This returns everything in the original string after (but not including) the most recently matched character.

For example, the following code:


myString = "Hello, Cleveland!";
alert ( myString.replace(/ /, " $' ") );

...displays an alert saying, "Hello, Cleveland! Cleveland!".

Replacement with a function

You can also use a function to provide the replacement text for the replace() method. For example:


myString = "Hello, Cleveland!";
alert ( myString.replace(/(Hello)/, function($1) {return $1.toUpperCase()} ) );

This uses an anonymous function for the replacement value. The function takes the $1 special variable as an argument (which if you remember is the text that matches the first bit in parentheses from the regular expression, in this case "Hello"), and returns the value as an upper-case string.

This example displays an alert saying, "HELLO, Cleveland!".

search()

stringObject.search ( expression )

slice()

stringObject.slice ( start [, end ] )

Extracts the portion of the string between the index start and the end of the string. If end is specified, then it extracts the portion between start and the character before the one at index end.

String indices start from zero, so the first position is 0 and the last is stringObject.length - 1.

If the start or end indices are negative, then they work from the end of the string, rather than the beginning.

For example:


myString = "Their appeal is becoming more selective.";
alert ( myString.slice(6,12) );    // Displays 'appeal'
alert ( myString.slice(25) );      // Displays 'more selective.'
alert ( myString.slice(25,-1) );   // Displays 'more selective'
alert ( myString.slice(-15,-11) ); // Displays 'more'

small()

stringObject.small ( )

Returns the string formatted in small text - it's the equivalent of the HTML <small></small> element:


myString = "Their appeal is becoming more selective.";
document.write ( myString.small() );

The above code has the same effect as the following HTML:


<small>Their appeal is becoming more selective.</small>

split()

stringObject.split ( delimiter [, count] )

Splits stringObject into an array of smaller strings. delimiter determines at what points to split the string. It can be a single character, a string or a regular expression. If delimiter is an empty string (""), split() splits the string at every character.

The optional count parameter determines how many times the split should occur. If it's omitted then the split will be made as many times as possible.

Examples:


myString = "You don't do heavy metal in doubly";
subStrings = myString.split(" ");
alert ( subStrings );

This brings up an alert box displaying the resulting subStrings array as: "You,don't,do,heavy,metal,in,doubly".


myString = "You don't do heavy metal in doubly";
subStrings = myString.split(" ",3);
alert ( subStrings );

This brings up an alert box displaying the resulting subStrings array as: "You,don't,do".


myString = "You don't do heavy metal in doubly";
subStrings = myString.split("metal");
alert ( subStrings );

This brings up an alert box displaying the resulting subStrings array as: "You don't do heavy , in doubly".

strike()

stringObject.strike ( )

Returns the string formatted as strike-through text - it's the equivalent of the HTML <strike></strike> element:


myString = "Their appeal is becoming more selective.";
document.write ( myString.strike() );

The above code has the same effect as the following HTML:


<strike>Their appeal is becoming more selective.</strike>

The strike element is deprecated in HTML 4, and should not be used. Therefore it's best to avoid using the strike() method too.

sub()

stringObject.sub ( )

Returns the string formatted as subscript text - it's the equivalent of the HTML <sub></sub> element:


myString = "Their appeal is becoming more selective.";
document.write ( myString.sub() );

The above code has the same effect as the following HTML:


<sub>Their appeal is becoming more selective.</sub>

substr()

stringObject.substr ( start [, length] )

Extracts length characters from the string starting from the index start. If length is omitted, then it extracts the portion between start and the end of the string.

String indices start from zero, so the first position is 0 and the last is stringObject.length - 1.

If the start index is negative, then it works from the end of the string, rather than the beginning.

For example:


myString = "Their appeal is becoming more selective.";
alert ( myString.substr(6,6) ); // Displays 'appeal'
alert ( myString.slice(-15) );  // Displays 'more selective.'

substring()

stringObject.substring ( start [, end] )

This function is nearly identical to slice(). The only difference is that you can't use negative values for the indices.

sup()

stringObject.sup ( )

Returns the string formatted as superscript text - it's the equivalent of the HTML <sup></sup> element:


myString = "Their appeal is becoming more selective.";
document.write ( myString.sup() );

The above code has the same effect as the following HTML:


<sup>Their appeal is becoming more selective.</sup>

toLowerCase()

stringObject.toLowerCase ( )

Returns the string converted to all lower-case letters.

toString()

object.toString ( )

Returns a string representation of an object.

Example:


myArray = new Array ( );
myArray[0] = "David";
myArray[1] = "Nigel";
myArray[2] = "Derek";
alert ( myArray.toString() );   // Displays 'David,Nigel,Derek'

toUpperCase()

stringObject.toUpperCase ( )

Returns the string converted to all upper-case letters.

valueOf()

stringObject.valueOf ( )

Returns the value of stringObject as a primitive string. Equivalent to toString().


That's pretty much all the methods of the String object. There are quite a few! You now know practically everything there is to know about working with strings in JavaScript.

Follow Elated

Related articles

Responses to this article

There are no responses yet.

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page