Chapter 28. The String Object


  • How to parse and work with text

  • Performing search-and-replace operations

  • Scripted alternatives to text formatting

Chapter 6's tutorial introduced you to the concepts of values and the types of values that JavaScript works with—features, such as strings, numbers, and Boolean values. In this chapter, you look more closely at the very important String data type, as well as its relationship to the Number data type. Along the way, you encounter the many ways in which JavaScript enables scripters to manipulate strings.


Much of the syntax that you see in this chapter is identical to that of the Java programming language. Because the scope of JavaScript activity is much narrower than that of Java, you don't have nearly as much to learn for JavaScript as for Java.

String and Number Data Types

Although JavaScript is what is known as a "loosely typed" language, you still need to be aware of several data types because of their impact on the way you work with the information in those forms. In this section, I focus on strings and two types of numbers.

Simple strings

A string consists of one or more standard text characters placed between matching quote marks. JavaScript is forgiving in one regard: You can use single or double quotes, as long as you match two single quotes or two double quotes around a string. A major benefit of this scheme becomes apparent when you try to include quoted text inside a string. For example, say that you're assembling a line ...

Get JavaScript® Bible, Sixth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.