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

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

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"
 id="result"></textarea></div>

<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).

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020