1. Technology

JavaScript By Example

Objects: 7. String


Simiilar to the way the Number oblect provides methods for number manipulation, the String object provides methods for string manipulation. As with numbers where you can just let the numbers be converted automatically to Number objects when you need to use the methods, you do the same with text strings.

To define a text string you can enclose the text inside either single or double quotes. Unlike some other languages it makes no difference to JavaScript which of the two you use as they are both treated exactly the same so you might as well use whichever keeps the number of characters in the text that need to be escaped to a minimum.

The \ is used as an escape character and so all \ that actually belong in your text string need to be entered as \\ instead. The main characters you would need to escape in a plain text string are single quotes inside a single quoted string and double quotes inside a double quoted string but there are also a few escape characters to represent new lines, form feeds, tabs etc. that you may also need to use on occasion.

var txt, txt2, txt3;
txt = 'This isn\'t a test.';
txt2 = new String("This also isn't a test");

if (txt.substr(0,4) === txt2.substr(0,4))
  txt3 = 'The first four characters are the same.';

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Objects
  7. JavaScript By Example - Objects: String

©2014 About.com. All rights reserved.