JavaScript: Strings

Chapter 12.4 Pg383-392

Strings are sequences of characters. In JavaScript, we can make a string by just enclosing a set of characters in quotes.

var s = "this is a string";
You can use either single or double quotes. If you want one kind of quote in a string, use the other to wrap around it. If you want to put a special character in a string, like a quote or a tab, you can 'escape' it using a backslash. Strings are a kind of object in JavaScript and have a few useful methods. When processed or validating forms, you may need these.

Notes Code Results
Escaping quotes var s = "In this string the word \"with\" has quotes around it";
document.write(s);
You may need to get the length of a string, which can be done like this: var s = "this is a string";
document.write("The length of s is " + s.length);
To find the last character in a string var s = "this is a string";
document.write("The last character of s is " + s.charAt(s.length - 1));
Here is how you can get the last 6 characters. Remember, that the first character in a string is character 0, not 1. var s = "this is a string";
var s2 = s.substring(10,s.length);
document.write("The last 6 characters of s are " + s2);
If you want to find out where the '-' is in a phone number, do this: var s = "(630) 393-1788";
var dashpos = s.indexOf('-');
document.write("The last - is at position " + dashpos);
Wrap a string in link and bold tags var linkstr = "home page".bold();
document.write(linkstr.link("http://www.archie-perkins.com"));
replace the area code in the phone number var s = "(630) 393-1788";
var s3 = s.replace(/\(.*\)/,"(708)");
document.write("new number is " + s3);
break a string into an array var p = "630.393.1788";
var parts = p.split(".");
document.write("area code is " + parts[0] + " ");
document.write("exchange is " + parts[1] + " ");
document.write("line is " + parts[2]);