Strings are sequences of characters. In JavaScript, we can make a string by just enclosing a set of characters in quotes.
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]); |