String Objects and String Literals in JavaScript


Table of content:

Introduction to the String Object

The String object has properties and methods that allow you to get information about strings and modify them. String objects can be created in two ways: using the new keyword with the construction function or JavaScript creates one temporarily when one of the methods is called from a string literal.

The String Object

You can create a String object using the new keyword.

var InstanceName = new String("string value");

String objects are commonly used when comparing String objects, although string literals are used more often.

The String Literal

A String literal is created by assigning string literal to a variable. This still allows you to use the methods of the String object (and one of the properties).

var HondaString = "PCX";

With text strings you are also allowed to use the properties and methods of the String object.

String object vs. String literal

In order to see the difference, we are going to create two scripts which at the first glance will have the same result.

var HondaString1 = "PCX";
var HondaString2 = "PCX";
if (HondaString1 == HondaString2) {
	window.alert("Same strings!");
}
else {
	window.alert("Not the same strings!");
}

The result is what you would expect, an alert that says “Same strings!”.

However, if you use String objects you would see something unexpected.

var HondaString1 = new String("PCX");
var HondaString2 = new String("PCX");
if (HondaString1 == HondaString2) {
	window.alert("Same strings!");
}
else {
	window.alert("Not the same strings!");
}

This time the alert tells you “Not the same strings!”. That’s because a String object is an object value not a literal value.

A regular text string is able to use the String object’s methods because JavaScript take the string literal and transforms it into a temporary String object. It returns to a string literal immediately after the method’s execution is complete.

Back to top

Properties of the String Object

The string object has only three properties shown in the table below.

PropertyPurpose
constructorHolds the value of the constructor function for an instance of the object.
lengthHolds the numeric value of the length of the string (number of characters).
prototypeAllows you to add properties to the object.

Back to top

The Constructor Property

The constructor property performs the same task as it does in the other objects that have it (Date objects and Array objects for example). It sends back the value of the constructor function. To use the constructor property you have to use a String object, not a string literal. Only the length property allows you to use a string literal, and all of the methods. For constructor and prototype properties String objects to be used are required.

var HondaString = new String("PCX");
document.write(HondaString.constructor);

The output would be “function String() { [native code] }”.

Back to top

The Length Property

The length property returns the length of the string. It can be used with both String objects and string literals.

var HondaString = "PCX";
document.write(HondaString.length);

The length property is useful when you want to break strings apart to get information or make changes to them, especially if the viewer enters the string and you don’t know its length.

Back to top

The Prototype Property

The prototype property is used to add properties or methods to String objects.

String.prototype.appearance = "cool";
var HondaString = new String("PCX");
window.alert("Honda PCX is " + HondaString.appearance);

The String object “PCX” has an “appearance” property of “cool”.

Back to top

Methods of the String Object

The String Object has 29 methods shown in the table below.

MethodPurpose
anchor()Creates an HTML anchor tag with a target on a page.
big()Adds <big> and </big> tags around a string value.
blink()Adds <blink> and </blink> tags around a string value.
bold()Adds <b> and </b> tags around a string value.
charAt()Finds out which character is at a given position in a string.
charCodeAt()Finds the character code of a character at a given position in a string.
concat()Adds two or more strings together and returns the new combined string value.
fixed()Adds <tt> and </tt> tags (not used in HTML5) around a string value.
fontcolor()Adds <font color=”color”> and </font> tags around a string value.
fontsize()Adds <font size=”number”> and </font> tags around a string value.
fromCharCode()Uses character codes sent as parameters to create a new string.
indexOf()Searches for a character sent as parameter in a string. If it is found then it returns the position of the first instance of the character, otherwise it returns -1.
italics()Adds <i> and </i> tags around a string value.
lastIndexOf()Searches for a character sent as parameter in a string. If it is found then it returns the position of the last instance of the character, otherwise it returns -1.
link()Creates HTML links using the string as the link text and linking to the URL sent as a parameter.
match()Compares a regular expression and a string to see if they match.
replace()Finds out if a regular expression matches a string then replaces a matched string with a new one.
search()Executes the search for a match between a regular expression and a specified string.
slice()Pulls out a specified section of a string value and returns a new string.
small()Adds <small> and </small> tags around a string value.
split()Separates a string into an array of strings based on a character sent as a parameter to the method.
strike()Adds <strike> and </strike> tags around a string value.
sub()Adds <sub> and </sub> tags around a string value.
substr()Allows a portion of the string specified with a starting position and ending after a certain number of characters to be returned.
substring()Allows a portion of the string specified with a starting and ending position to be returned.
sup()Adds <sup> and </sup> tags around a string value.
toString()Returns the string literal value of a String object.
toLowerCase()Converts a string to all lowercase letters then returns the result.
toUpperCase()Converts a string to all uppercase letters then returns the result.

Back to top

Methods that add HTML tags

Many of the methods of the String object are methods that create HTML tags around a string. Some of these methods can create HTML tags with attribute values sent to them as parameters. Many of these effects can be achieved using more up to date methods of accessing an element’s style and/or innerHTML() properties.

The basic methods big(), blink(), bold(), fixed(), italics(), small(), strike(), sub(), and sup() simply add a basic HTML tag around a string.

var hondaBike = "Honda is awesome!";
var bigHonda = hondaBike.big();
var boldHonda = hondaBike.bold();
var fixedHonda = hondaBike.fixed();
var italicsHonda = hondaBike.italics();
var smallHonda = hondaBike.small();
var strikeHonda = hondaBike.strike();
var subHonda = hondaBike.sub();
var supHonda = hondaBike.sup();

document.write(hondaBike + " - no method" + "<br>");
document.write(bigHonda + " - big() method" + "<br>");
document.write(boldHonda + " - bold() method" + "<br>");
document.write(fixedHonda + " - fixed() method" + "<br>");
document.write(italicsHonda + " - italics() method" + "<br>");
document.write(smallHonda + " - small() method" + "<br>");
document.write(strikeHonda + " - strike() method" + "<br>");
document.write("sample " + subHonda + " - sub() method" + "<br>");
document.write("sample " + supHonda + " - sup() method" + "<br>");

Back to top

The anchor() method

The anchor() method places a text string as the text for a named anchor. The anchor() method takes a parameter that will be the name attribute for the named anchor.

<a name="parameter_string">text_string</a>

The parameter_string is a string that you send as parameter in the method call. The text_string is the value of the string from which you call the method.

var anchor_text = "Part 1";
var fullAnchor = anchor_text.anchor();
document.write(fullAnchor);

Basically, the code writes “<a name=”Part 1″>Part 1</a>” into the code of the page.

Back to top

The fontcolor() method

The fontcolor() method adds font color to the text string that is used to call it. It takes in a string parameter that indicates what color the text should be.

var text_initial = "I should be blue!";
document.write(text_initial);
document.write(text_initial.fontcolor("blue"));
document.write(text_initial.fontcolor("#3399ff"));
//Compare the three "document.write()

Back to top

The fontsize() method

The fontsize() method adjusts the font size of the text string that calls the method.

var smallText = "This text is small!";
document.write(smallText);
document.write(smallText.fontsize(5));

Back to top

The link() method

The link() method creates a hyperlink on the page. It takes in a string parameter that is the value of the URL and the text for the link will be the text string that called the method.

var linkText = "Saigon Website";
var fullLink = linkText.link("http://www.saigon.ro");
document.write(fullLink);

Back to top

The charAt() method

The charAt() method determins which element resides at a particular position in a string. When you want to find a character remember that the position count starts at 0.

var someText = "Character";
var firstCharAt = someText.charAt(0);
document.write(someText + " - first character is: " + firstCharAt.fontcolor("red");

Finding the first character is quite easy. What happen if you want to find the last character but you don’t know how many characters are there in the string. For that we use the length property. Don’t forget that the length property returns the number of the characters of a string and the count starts at 1 (not at 0).

var someTextLastCharacter = "Find the last character";
var positionLast = someTextLastCharacter.length-1;
var lastCharacter = someTextLastCharacter.charAt(positionLast);
document.write(someTextLastCharacter);
document.write("The string has " + positionLast + " characters");
document.write("The last character is " + lastCharacter);
document.write(someTextLastCharacter.charAt(22));

Back to top

The charCodeAt() method

The charCodeAt() method returns the charactercode for the character at the position sent as parameter.

var textCharCoode = "Hello world";
var char_code = textCharCoode.charCodeAt(0);
document.write(char_code);

The code will ouput the numeric part of the code of the first character of the string which in the letter “H”.
Since the code of the letter “H” is &#72;, the script will output just “72”.

The concat() method

The concat() method combines the text string that calls the method with any number of other strings sent as parameters and returns the combined value.

var text_1 = "I wake up ";
var text_2 = "then ";
var text_3 = "I brush my teeth ";
document.write(text_1.concat(text_2,text_3));

Or, you can do it from the end to the beginning:

var text_1 = "I wake up ";
var text_2 = "then ";
var text_3 = "I brush my teeth ";
document.write(text_3.concat(text_2,text_1));

Back to top

The fromCharCode() method

The fromCharCode() method creates a string from a series of character codes sent as parameters to the method. It is the viceversa of charCodeAt() method.

document.write(String.fromCharCode(72,101,108,108,111));

The code converts the character codes into actual letters. It will display “Hello”.

Back to top

The indexOf() method

The indexOf() method finds out where a certain character begins within a string.

var text_cu_position = "Where is the letter e?";
var position_of_e = text_cu_position.indexOf("e");
document.write("The character e starts at position " + position_of_e);

The code will output “The character e starts at position 2”. Although the letter “e” is the third letter in the string.

Note:
“E” and “e” are two different characters in this situation. If you ask for the indexOf("E") the result will be -1 since there is no “E” in our string.

It might be confussing to get the message “The character e starts at position -1”. If you want a different message in this situation then you can use a code like below.

var text_cu_position_2 = "Where is the capital f?";
document.write(text_cu_position_2)
var position_of_F = text_cu_position_2.indexOf("F");
	if (position_of_F == -1) {
		document.write("
" + "The character is not in the string!"); } else { document.write("The character starts at the position " + position_of_F); }

You can search for the wanted character started with a specified position by adding a second parameter to the indexOf() method.

var sampleText = "The third occurrence of the letter e.";
var positionE = sampleText.indexOf("e",3);
document.write("The third occurrence of the letter e in your string is at the position " + positionE);

If you want your string to contain the word “Honda” in it and not “Yamaha” then you can use the following code.

var sampleHonda = "I like Honda!";
if ( sampleHonda.indexOf("Honda") != -1 && sampleHonda.indexOf("Yamaha") ==-1 ) {
	document.write("Yes, Honda is good!");
}
else {
	document.write("You should consider Honda rather than Yamaha!");
}

Back to top

The lastIndexOf() method

The lastIndexOf() method finds out where the last instance of a certain character or string is located in the string.

var lastIndex_e = "Where is the last e in the string?";
var last_e_position = lastIndex_e.lastIndexOf("e");
document.write(lastIndex_e + "It is at the position " + last_e_position);

Back to top

The match() method

The match() method compares a regular expression with a string to see if they match. See “Regular Expressions” chapter for details.

Back to top

The replace() method

The replace() method finds out if a regular expression matches a string then replaces it with a new string. See “Regular Expressions” chapter for details.

Back to top

The search() method

The search() method executes a serch for a match between a regular expression and a specified string. See “Regular Expressions” chapter for details.

Back to top

The slice() method

The slice() method pulls out a part of a string and returns it as a new string.

var theString = "A part of this string will be cut.";
var cutString = theString.slice(0,21);
document.write(cutString);

The numeric parameters tell where to begin and end the string that is pulled.

Back to top

The split() method

The split() method creates an array of strings. The string is split based on a charater sent as
parameter.

var theString2 = "Honda , Yamaha , Suzuki";
var splitString = theString2.split(",");
var endCount = splitString.length;
for (var count = 0; count < endCount; count ++) {
	document.write(splitString[count] + "
"); }

The comma is sent as a parameter so it doesn’t end up in the array. The third line of the code gets the length of the splitString array and places that value in the variable endCount. The information is then used to loop through the array and print its elements on the page.

Back to top

The substr() method

The substr() method works just like the slice() method. The difference is that the second numeric parameter represents the number of characters to be pulled out.

Back to top

The substring() method

The substring() method allows you to send parameters for the beginning and the end positions of the string that you want to remove. It returns the removed portion of the string.

var theString3 = "Honda, Yamaha, Suzuki";
var substringString = theString3.substring(7,21);
document.write(substringString);

Back to top

The toString() method

The toString() method returns a string literal value for a string object that calls it.

var stringObject = new String("Honda");
var stringLiteral = stringObject.toString();
document.write(stringLiteral);

Back to top

The toLowerCase() method

The toLowerCase() method writes the value of a string in lowercase letters.

var capitalLetters = "STRING WRITTEN IN CAPITAL LETTERS.";
var stringLowercase = capitalLetters.toLowerCase();
document.write(stringLowercase);

Back to top

The toUpperCase() method

The toUpperCase() method writes the value of a string in uppercase letters.

var lowercaseLetters = "string written in lowercase letters.";
var stringUppercase = lowercaseLetters.toUpperCase();
document.write(stringUppercase);

Back to top

Regular expressions

Regular expressions allow you form patterns that can be matched against strings.

You can create a script that checks the format of an email address entered by a user (at least one character at the beginning followed by @ then a domain name etc).

Regular expressions are created by creating an instance of the JavaScript RegExp object. In the case of the regular expressions, the quotes are replaced by slashes (/).

var variable_name = /the_pattern/flags;

A very simple regular expression is the one that looks for an exact match of characters.

var matchThis = /an/;

If you test it against “and”, “ant”, “any” or “anger” then it is a match.

In order to perform this test you use the test() method of the RegExp object.

var matchThis = /an/;
matchThis.test("any");

The test() method returns a Boolean value of true or false. It is case sensitive.

var theName = window.prompt("Enter your name","");
var matchThis = /Dan/;
var testForMatch = matchThis.test(theName);
	if (testForMatch) {
		window.alert("We have the same name!");
	}
	else {
		window.alert("Your name is " + theName + " but my name is Dan.");
	}

Back to top

Adding Flags

Flags allow you to make the case insensitive or to look for every match in the string (not just for the first one, global test). Flags are added after the last slash in the regular expression. Let’s take the same code as we used above and make it case insensitive.

var theName = window.prompt("Enter your name","");
var matchThis = /Dan/i;
var testForMatch = matchThis.test(theName);
	if (testForMatch) {
		window.alert("We have the same name!");
	}
	else {
		window.alert("Your name is " + theName + " but my name is Dan.");
	}

Now, “dan”, “daN”, “dAn”, “DAN”, “DAn”, “DaN”, “dAN” and “Dan” will be a match! You can use one, two or all three flags at a time.

var matchThis = /Dan/ig;

Reguar Expression Flags table:

FlagPurpose
iMakes the match case insensitive
gMakes the match global
mMakes the match work in multiline mode

Back to top

Regular Expression Codes

The table below lists a number of characters to help you create very powerful patterns.

CharacterPurposeExample
^Matches only from the beginning of a line/^c/ matches “c” in “car”
/^c/ doesn’t match “c” in “accord”
$Matches only at the end of the line/$r/ matches “r” in “car”
/$r/ doesn’t match “r” in “promise”
*Matches the character preceding it if the character occurs zero or more times/co*/ matches “co” or “c”
/co*/ doesn’t match “si”
+Matches the character preceding it if it occurs one or more times/co+/ matches “co” or “cooo”
/co+/ doesn’t match “ca”
?Matches the character preceding it if it ooccurs zero or one time/o?|/ matches “style” or “column”
/o?|/ doesn’t match “cool”
.Matches any individual character excluding the newline character/.l/ matches “al” or “@l”
/.l/ doesn’t match “\nl” or “l”
(x)By replacing x with characters, matches that sequence and keeps it in memory to be used later: used for grouping of expressions/(a)/ matches “a”
/(Honda)/matches “Honda”
/(Honda)/ does not match “Yamaha”
|Used as a logical OR symbol to allow a match of what is on the left of the symbol OR what is on its right/Honda|Yamaha/ matches “Honda”
/Honda|Yamaha/ matches “Yamaha”
/Honda|Yamaha/ does not match Suzuki
{x}Using a number to replace x, matches when there are exactly x occurances of the character preceding it/n{1}/ matches “n”
/nn{2}/ matches “nnn”
/nn{1}/ does not match “nnn”
{x,}Using a number to replace x, matches when there are exactly x or more occurances of the character preceding it/n{1,}/ matches “n”
/n{1,}/matches “nnnn”
/n{3,}/ does not match “nn”
{x,y}Using numbers to replace x and y, matches when there are at least x occurances of the character preceding it but not more than y occurences of it/n{1,2}/ matches “n”
/n{1,2}/ matches “nn”
/n{2,3}/ does not match “n”
/n{4,7}/ does not match “nnn”
[]Matches a character set of your choice; will match when any one of the characters in the brackets (such as [abc]) or any one of the range of characters (such as [a-p]) is present/[abc]/ matches “a”
/[abc]/ matches “b”
/[abc]/ matches “c”
/[a-p]/matches “e”
/[a-p]/does not match “s”
[^]Matches when the characters in your character set are not present; may be a set (such as [abc]) or a range (such as [a-p])/[abc]/ matches “d”
/[abc]/ does not match “c”
/[a-p]/ matches “s”
/[a-p]/ does not match “c”
\Used to escape special characters or to make a normal character special\@ escapes “@” character
\n represents a new line character
[\b]Matches a BACKSPACE keystroke/[\b]/ matches a backspace
\bMatches when the character before or after it is located at the word boundary, such as before or after a space character; to match the beginning of a word, place the character to the right of the symbol (\bc); to match the end of a word, place the character to the left (c\b)/\bc/ matches “c” in “my car”
/\bm/ matches “m” in “my car”
/\bc/ does not match “c” in “accent”
/\bm/ does not match “m” in “Sam”
/m\b/ matches “m” in “Sam”
/c\b/ matches “c” in “Mac Pro”
/m\b/ does not match “m” in “computer”
/c\b/ does not match “c” in “my car”
\BMatches a character that is not located at a word boundary/\Ba/ matches “a” in “car”
/\Bc/ does not match “c” in “car”
\cXUsing a letter character to replace X, matches when the user presses the CTRL key followed by typing the letter X/\cX/ matches CTRL-X
/\cY/ matches CTRL-Y
/\cS/ does not match CTRL-Z
\dMatches if the character is a single numeric character/\d/ matches “4”
/\d/ does not match “s”
\DMatches a single character if it is not a numeric character/\D/ matches “a”
/\D/ does not match “4”
\fMatches if there is a form feed/\f/ matches a form feed
\nMatches if there is a new line/\n/ matches a new line
\rMatches if there is a carriage return/\r/ matches a carriage return
\sMatches a single character if it is a white space (such as a space or a new line)/\s/ matches the space in “b c”
/\s/ matches the tab in “b c”
/\s/does not match “bc”
\SMatches a single character if it does not represent white space/\S/ matches “d”
/\S/ does not match a blank space
\tMatches if there is a tab/\t/ matches the tab in “b c”
\vMatches if there is a vertical tab/\v/ matches a vertical tab
\wMatches any single character if it is a letter, number, or underscore/\w/ matches “4”
/\w/ does not match “@”
\WMatches any single character that is not a letter, number, or underscore/\W/ matches “@”
/\W/ does not match “4”

Back to top

Creating Patterns

Normally, in real life, you will probably need to create less exact patterns, that means you will be looking to match a more general pattern. You can verify strings acording to the standards you decide to set.

Let’s say that you want to make sure a text field contains one or more digits, you could use /d and + characters from the Regular Expression Codes Table as it is shown in the example below.

<!-- The HTML -->
<form>
Enter numbers:
<input type="text" id="has_digits" />
<input type="button" id="t_btn" value="Test" onclick="myFunction();" /><
</form>

<!-- The JavaScript -->
var t_buttonn = document.getElementById("t_btn");
function myFunction () {
	var has_num = document.getElementById("has_digits").value;
	var tomatch = /^\d+$/;
	if (tomatch.test(has_num)) {
		window.alert("Bravo, you entered only numbers!");
		}
	else {
		window.alert("I need only numbers!");
		}
}

Back to top

Grouping Expressions

Expressions surrounded by parentheses ({}) indicates a group that can be stored for later use in the expression. You can also use the match() method to store each match of a group along with the overall match in an array.

/3{5}/

This will match five instances of number 3.

/3{5,10}/

This will match number 3 if it occures at least 5 times but not more than 10 times.

/(3\d){5}/

This will match five instances of number 3 if it is followed by a character that is a digit. The reason that 3 and /d are between parentheses is that you need a set of two numbers, the first one to be 3.

Back to top

The replace(), match(), and search() methods

The replace() method

To replace information in a string you can use regular expressions and the replace() method of the String object.

For example, if you want to replace the fist instance of "Honda" with "Yamaha" you can use the following code.

var theString = "I love Honda because Honda is better than others!";
var toReplace = /Honda/;
var newTheString = theString.replace(toReplace,"Yamaha");
document.write(newTheString);

This replaces only the first instance of "Honda". If you want to replace all instances of "Honda" then you can make the match global by adding the g flag.

var theString = "I love Honda because Honda is better than others!";
var toReplace = /Honda/g;
var newTheString = theString.replace(toReplace,"Yamaha");
document.write(newTheString);

The match() method

The match() method compares a regular expression and a string to see if they match. It returns an array that contains one or more matches. If no match is found then it returns -1.

var myString = "I am Ironman!";
var toMatch = /Iron/;
if (myString.match(toMatch)) {
	window.alert("Your string contains Iron!");
}
else {
	window.alert("No Iron in your string!");
}

The search() method

The search() method executes the search for a match between a regular expression and a specified string. If a match is found then it returns the position in the string where the beginning of the match was found. If no match is found then it returns -1.

var myString = "I own a Honda. Honda bikes are great. Definitely, Honda is better than other bikes.";
document.write(myString);
var toMatch = /Honda/;
document.write("Now I am going to search for the word 'Honda' in the above string");
if (myString.search(toMatch)) {
	document.write("'Honda' found at position " + myString.search(toMatch) + "!");
}
else {
	document.write("Sorry, no Honda found!");
}

Back to top

Leave a Reply