Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
This chapter is from the book

Working with Strings

Strings and numbers are two of the most common types used in JavaScript, and both are easy to comprehend and use. You’ve seen the fundamentals when it comes to numbers—and there’s not all that much to it, really, so now it’s time to look at strings in more detail.

Creating Strings

Informally, you’ve already witnessed how strings are created: just quote anything. As with a number, once you have a string value, you also have predefined methods that can be used to manipulate that value. Unlike numbers, though, strings have a lot more methods, and even a property you’ll commonly use: length. The length property stores the number of characters found in the string, including empty spaces:

var fullName = 'Larry Ullman';

fullName.length; // 12

If you’re following this book sequentially, you’ll have already seen this in Chapter 2:

var email = document.getElementById('email');

if ( (email.value.length > 0) { ...

What you’re actually seeing here is the beauty of object-oriented programming: A string is a string, with all the functionality that comes with it, regardless of how the string was created. The assignment to the email variable starts with the document object, which is a representation of the page’s HTML. That object has a getElementById() method, which returns an HTML element. The specific element returned by that line is a text input, in other words, a text object. This is assigned to email. That object has a value property for finding the text input’s value (or for setting its value). Since the value returned by that property is a string, you can then refer to its length property. Thanks to the ability to chain object notation, this could be reduced to one line:

if ( (document.getElementById('email').value.length > 0) { ...

Deconstructing Strings

Once you’ve created a string, you can deconstruct it—break it into pieces—in a number of ways. As a string is just a sequence of length characters, you can reference individual characters using the charAt() method. This method takes an index as its first argument, an index being the position of the character in the string. The trick to using indexes is that they begin at 0, not 1 (this is common to indexes of all types across all programming languages). Thus, the first character of string fullName can be retrieved using fullName.charAt(0). And a string’s last character will be indexed at length - 1:

var fullName = 'Larry Ullman';

fullName.charAt(0); // L

fullName.charAt(11); // n

Sometimes you don’t want to know what character is at a specific location in the string, but rather if a character is found in the string at all. For this need, use the indexOf() method. This method returns the indexed position where the character is first found:

var fullName = 'Larry Ullman';

fullName.indexOf('L'); // 0

fullName.indexOf('a'); // 1

fullName.indexOf(' '); // 5

The first argument can be more than a single character, letting you see if entire words are found within the string. In that case, the method returns the indexed position where the word begins in the string:

var language = 'JavaScript';

language.indexOf('Script'); // 4

The indexOf() method takes an optional second argument, which is a location to begin searching in the string. By default, this is 0:

var language = 'JavaScript';

language.indexOf('a'); // 1

language.indexOf('a', 2); // 3

However you use indexOf(), if the character or characters—the needle—is not found within the string (the haystack), the method returns −1. Also, indexOf() performs a case-sensitive search:

var language = 'JavaScript';

language.indexOf('script'); // -1

Another way to look for needles within a string haystack is to use lastIndexOf(), which goes backward through the string. Its second argument is also optional, and indicates the starting point, but the search again goes backward from that starting point, not forward:

var fullName = 'Larry Ullman';

fullName.indexOf('a'); // 1

fullName.lastIndexOf('a'); // 10

fullName.lastIndexOf('a', 5); // 1

To pull a substring out of a string, there’s the slice() method. Its first argument is the index position to begin at. Its optional second argument is the indexed position where to stop. Without this second argument, the substring will continue until the end of the string:

var language = 'JavaScript';

language.slice(4); // Script

language.slice(0,4); // Java

A nice trick with slice() is that you can provide a negative second argument, which indicates the index at which to stop, counting backward from the end of the string. If you provide a negative starting point, the slice will begin at that indexed position, counting backward from the end of the string:

var language = 'JavaScript';

language.slice(0,-6); // Java

language.slice(-6); // Script

However you use slice(), this method only returns a new string, without affecting the value of the original.

JavaScript also has a substring() method, which uses the same arguments as slice(), but it has some unexpected behaviors, and it’s recommended that you use slice() instead.

JavaScript has another string method for retrieving substrings: the aptly named substr(). Its first argument is the starting index for the substring, but the second is the number of characters to be included in the substring, not the terminating index. In theory, you can provide negative values for each, thereby changing both the starting and ending positions to be relative to the end of the string, but Internet Explorer doesn’t accept negative starting positions.

To test using slice(), let’s create some JavaScript code that limits the amount of data that can be submitted by a textarea. For the time being, a second textarea will show the restricted string; in Chapter 8, Event Handling, you’ll learn how to dynamically restrict the amount of text entered in a text area in real time. The relevant HTML for this example is:

<div><label for="comments">Comments</label><textarea name="comments"
 id="comments" maxlength="100" required></textarea></div>

<div><label for="count">Character Count</label><input type="number"
 name="count" id="count"></div>

<div><label for="result">Result</label><textarea name="result"

<div><input type="submit" value="Submit" id="submit"></div>

The HTML form has one textarea for the user’s input, a text input indicating the number of characters used, and another textarea showing the truncated result. To make the truncated text more professional, it’ll be broken on the final space before the character limit (Figure 4.9), rather than having the text broken midword. The page, named text.html, includes the text.js JavaScript file, to be written in subsequent steps.

Figure 4.9.

Figure 4.9. The HTML form, as it works in Internet Explorer.

To deconstruct strings:

  1. Create a new JavaScript file in your text editor or IDE, to be named text.js.
  2. Begin defining the limitText() function:
    function limitText() {
       'use strict';
       var limitedText;

    The limitedText variable will be used to store the edited version of the user-supplied text.

  3. Retrieve the original text:
    var originalText = document.getElementById('comments').value;

    The original text comes from the first textarea in the form and is assigned to originalText here.

  4. Find the last space before the one-hundredth character in the original text:
    var lastSpace = originalText.lastIndexOf(' ', 100);

    To find the last occurrence of a character in a string, use the lastIndexOf() method, applied to the original string. This script is not looking for the absolute last space, though, just the final space before the hundredth character, so 100 is provided as the second argument to lastIndexOf(), meaning that the search will begin at the index of 100 and work backward.

  5. Trim the text to that spot:
    limitedText = originalText.slice(0, lastSpace);

    Next, a substring from originalText is assigned to limitedText, starting at the beginning of the string—index of 0—and stopping at the previously found space.

  6. Show the user the number of characters submitted:
    document.getElementById('count').value = originalText.length;

    To indicate that the user submitted too much data, the original character count will be shown in a text input.

  7. Display the limited text:
    document.getElementById('result').value = limitedText;

    The value of the second textarea is updated with the edited string.

  8. Return false and complete the function:
    return false;
    } // End of limitText() function.
  9. Add an event listener to the form:
    function init() {
       'use strict';
       document.getElementById('calcForm').onsubmit = limitText;
    } // End of init() function.
    window.onload = init;

    This is the same basic code used in the previous example. When the form is submitted, the limitText() function will be called.

  10. Save the file as text.js, in a js directory next to text.html, and test it in your Web browser (Figure 4.9).

Try using different strings (Figure 4.10), and retest, to make sure it’s working as it should.

Figure 4.10.

Figure 4.10. In Chrome, which supports the textarea’s maxlength attribute, only 100 characters can be submitted, but the partial word is still chopped off.

Manipulating Strings

The most common way to manipulate a string is to change its value using concatenation. Concatenation is like addition for strings, adding more characters onto existing ones. In fact, the concatenation operator in JavaScript is also the arithmetic addition operator:

var message = 'Hello';

message = message + ', World! ';

As with the arithmetic addition, you can combine the plus sign with the assignment operator (=) into a single step:

var message = 'Hello';

message += ', World! ';

This functionality is duplicated by the concat() method, although it’s less commonly used. This method takes one or more strings to be appended to the string:

var address = '100 Main Street';

address.concat(' Anytown', ' ST', ' 12345', ' US');

Two methods exist to simply change the case of the string’s characters: toLowerCase() and toUpperCase(). You can apply these to a string prior to using one of the previously mentioned methods, in order to fake case-insensitive searches:

var language = 'JavaScript';

language.indexOf('script'); // -1, aka not found

language.toLowerCase().indexOf('script'); // 4

Added to JavaScript in version 1.8.1 is the trim() method, which removes extra spaces from both ends of a string. It’s supported in more current browsers—Chrome, Firefox 3.5 and up, IE9 and above, Safari 5 and up, and Opera 10.5 and above, but isn’t available on older ones.

Note that, as with slice() and the other methods already covered, toLowerCase(), toUpperCase(), and trim() do not affect the original string, they only return a modified version of that string. Concatenation, however, does alter the original.

To test this new information, this next example will take a person’s first and last names, and then format them as Surname, First Name (Figure 4.11). The relevant HTML is:

<div><label for="firstName">First Name</label><input type="text" name="firstName" id="firstName" required></div>

<div><label for="lastName">Last Name</label><input type="text" name="lastName" id="lastName" required></div>

<div><label for="result">Formatted Name</label><input type="text" name="result" id="result" required></div>

<div><input type="submit" value="Submit" id="submit"></div>
Figure 4.11.

Figure 4.11. The values entered in the first two inputs are concatenated together to create a formatted name.

This would go into an HTML page named names.html, which includes the names.js JavaScript file, to be written in subsequent steps. By this point in the chapter, this should be a simple and obvious exercise for you.

To manipulate strings:

  1. Create a new JavaScript file in your text editor or IDE, to be named names.js.
  2. Begin defining the formatNames() function:
    function formatNames() {
        'use strict';
        var formattedName;

    The formattedName variable will be used to store the formatted version of the user’s name.

  3. Retrieve the user’s first and last names:
    var firstName = document.getElementById('firstName').value;
    var lastName = document.getElementById('lastName').value;
  4. Create the formatted name:
    formattedName = lastName + ', ' + firstName;

    To create the formatted name, assign to the formattedName variable the lastName plus a comma plus a space, plus the firstName. There are other ways of performing this manipulation, such as:

    formattedName = lastName;
    formattedName += ', ';
    formattedName += firstName;

    That code would probably perform worse, though, than the one-line option.

  5. Display the formatted name:
    document.getElementById('result').value = formattedName;
  6. Return false and complete the function:
        return false;
    } // End of formatNames() function.
  7. Add an event listener to the form:
    function init() {
       'use strict';
       document.getElementById('calcForm').onsubmit = formatNames;
    } // End of init() function.
    window.onload = init;

    When the form is submitted, the formatNames() function will be called.

  8. Save the file as names.js, in a js directory next to names.html, and test it in your Web browser (Figure 4.11).

Escape Sequences

Another thing to understand about strings in JavaScript is that they have certain meaningful escape sequences. You’ve already seen two examples of this: to use a type of quotation mark (single or double) within a string delimited by that same type, the inserted quotation mark must be prefaced with a backslash:

  • ‘I\’ve got an idea.’
  • “Chapter 4, \“Simple Variable Types\””

Three other meaningful escape sequences are:

  • \n, a new line
  • \r, a carriage return
  • \\, a literal backslash

Note that these work within either single or double quotation marks (unlike, for example, in PHP, where they only apply within double quotation marks).

  • + Share This
  • 🔖 Save To Your Account