JS Strings

What is String in JavaScript

A string is a series of letters, numbers, special symbols, and arithmetic values, or a mix of all these elements. You can create strings by wrapping the characters in either single quotes (') or double quotes ("). Here is an example:

var myString = 'Hello World!'; // Single quoted string
var myString = "Hello World!"; // Double quoted string

Quotes can be used inside a string as long as they differ from the quotes that enclose the string:

var str1 = "it's okay";
var str2 = 'He said "Goodbye"';
var str3 = "She replied 'Calm down, please'";
var str4 = 'Hi, there!"; // Syntax error - quotes must match

However, you can include single quotes within single-quoted strings or double quotes within double-quoted strings by using a backslash (\) to escape the quotes, like this:

var str1 = 'it\'s okay';
var str2 = "He said \"Goodbye\"";
var str3 = 'She replied \'Calm down, please\'';

The backslash (\) is known as an escape character, while the sequences \' and \" used in the example above are referred to as escape sequences.


JavaScript Escape Sequences

Escape sequences are also handy for using characters that can't be typed directly from the keyboard. Here are some of the most commonly used escape sequences:

  • \n represents a newline character
  • \t represents a tab character
  • \r represents a carriage-return character
  • \b represents a backspace character
  • \\ represents a single backslash (\)

Here's an example to illustrate how escape sequences actually work:

var str1 = "The quick brown fox \n jumps over the lazy dog.";
document.write("<pre>" + str1 + "</pre>"); // Create line break

var str2 = "C:\Users\Downloads";
document.write(str2); // Prints C:UsersDownloads

var str3 = "C:\\Users\\Downloads";
document.write(str3); // Prints C:\Users\Downloads

Performing Operations on Strings

JavaScript offers various properties and methods to manipulate string values. Technically, only objects can have properties and methods. However, in JavaScript, primitive data types can behave like objects when you use the property access notation (dot notation).

JavaScript accomplishes this by creating a temporary wrapper object for primitive data types. This is done automatically by the JavaScript interpreter in the background.

Getting the Length of a String

The length property returns the total number of characters in the string, including special characters like \t or \n.

var str1 = "This is a paragraph of text.";
document.write(str1.length); // Prints 28

var str2 = "This is a \n paragraph of text.";
document.write(str2.length); // Prints 30, because \n is only one character

 

Note: Since length is a property and not a function, do not use parentheses after it like str.length(). Instead, just write str.length; otherwise, it will cause an error.


Finding a String Inside Another String

You can use the indexOf() method to locate a substring within another string. This method returns the index or position of the first occurrence of a specified string.

var str = "If the facts don't fit the theory, change the facts.";
var pos = str.indexOf("facts");
alert(pos); // 0utputs: 7

Similarly, you can use the lastIndexOf() method to find the index or position of the last occurrence of a specified string within a string, like this:

var str = "If the facts don't fit the theory, change the facts.";
var pos = str.lastIndexOf("facts");
alert(pos); // 0utputs: 46

When you use the indexOf() or lastIndexOf() methods and the substring isn't found, both will give you -1. You can also include a number when you use these methods to specify where to start searching within the string. Let's see an example:

var str = "If the facts don't fit the theory, change the facts.";

// Searching forwards
var pos1 = str.indexOf("facts", 20);
alert(pos1); // 0utputs: 46

// Searching backwards
var pos2 = str.lastIndexOf("facts", 20);
alert(pos2); // 0utputs: 7

Remember: In a string, characters are numbered from left to right. The first character's index is 0, and for a string named myStr, the index of its last character is myStr.length - 1.


Finding a Pattern Within a String

You can utilize the search() method to look for specific text or patterns within a string.

Similar to the indexOf() method, search() returns the index of the initial match and -1 if no matches are found. However, unlike indexOf(), this method allows for more advanced search options by accepting a regular expression as its argument.

var str = "Color red looks brighter than color blue.";

// Case sensitive search
var pos1 = str.search("color");
alert(pos1); // 0utputs: 30

// Case insensitive search using regexp
var pos2 = str.search(/color/i);
alert(pos2); // 0utputs: 0

 

Note: Unlike the search() method, global searches are not supported. It disregards the g flag or modifier (for example, /pattern/g) in its regular expression argument.

You will explore more about regular expressions in the upcoming chapters.


Getting a Section of a String

You can employ the slice() method to retrieve a segment or part of a string.

This method requires two parameters: the starting index (the index from which extraction begins) and, optionally, the ending index (the index before which extraction ends), as shown in str.slice(startIndex, endIndex).

In the following example, a portion of a string is sliced from position 4 to position 15:

var str = "The quick brown fox jumps over the lazy dog.";
var subStr = str.slice(4, 15);
document.write(subStr); // Prints: quick brown

You can even use negative values. When negative, it's treated as strLength + startIndex, where strLength is the string's length (i.e., str.length). For instance, if startIndex is -5, it's handled as strLength - 5. If startIndex is equal to or greater than the string's length, the slice() method gives back an empty string. Additionally, if the optional endIndex isn't provided or is left out, slice() extracts to the string's end.

var str = "The quick brown fox jumps over the lazy dog.";
document.write(str.slice(-28, -19)); // Prints: fox jumps
document.write(str.slice(31)); // Prints: the lazy dog.

You can also utilize the substring() method to extract a portion of the given string based on start and end indexes, like str.substring(startIndex, endIndex). The substring() method is quite similar to the slice() method, with a few distinctions:

  • If either argument is less than 0 or is NaN, it's treated as 0.
  • If either argument is greater than str.length, it's treated as if it were str.length.
  • If startIndex is greater than endIndex, then substring() will swap those two arguments; for example, str.substring(5, 0) == str.substring(0, 5).

The subsequent example will demonstrate how this method actually functions:

var str = "The quick brown fox jumps over the lazy dog.";
document.write(str.substring(4, 15)); // Prints: quick brown
document.write(str.substring(9, 0)); // Prints: The quick
document.write(str.substring(-28, -19)); // Prints nothing
document.write(str.substring(31)); // Prints: the lazy dog.

Getting a Specific Number of Characters from a String

JavaScript also offers the substr() method, which resembles slice() with a slight difference: instead of an ending index, the second parameter specifies the number of characters to extract, like str.substr(startIndex, length). If length is 0 or a negative number, it returns an empty string. The example below illustrates its usage:

var str = "The quick brown fox jumps over the lazy dog.";
document.write(str.substr(4, 15)); // Prints: quick brown fox
document.write(str.substr(-28, -19)); // Prints nothing
document.write(str.substr(-28, 9)); // Prints: fox jumps
document.write(str.substr(31)); // Prints: the lazy dog.

Substituting Text within a String

You can employ the replace() method to swap part of a string with another string. This method requires two parameters: a regular expression to match or the substring to be replaced, and a replacement string, like str.replace(regexp|substr, newSubstr).

The replace() method generates a new string; it doesn't modify the original string, which remains unaltered. The example below illustrates its functionality:

var str = "Color red looks brighter than color blue.";
var result = str.replace("color", "paint");
alert(result); // 0utputs: Color red looks brighter than paint blue.

By default, the replace() method replaces only the first occurrence, and it's case-sensitive. To replace substrings within a string in a case-insensitive manner, you can employ a regular expression (regexp) with an i modifier, as demonstrated in the example below:

var str = "Color red looks brighter than color blue.";
var result = str.replace(/color/i, "paint");
alert(result); // 0utputs: paint red looks brighter than color blue.

Similarly, to replace all instances of a substring within a string in a case-insensitive manner, you can apply the g modifier along with the i modifier, like this:

var str = "Color red looks brighter than color blue.";
var result = str.replace(/color/ig, "paint");
alert(result); // 0utputs: paint red looks brighter than paint blue.

Changing a String to Uppercase or Lowercase

You can utilize the toUpperCase() method to transform a string into uppercase, like so:

var str = "Hello World!";
var result = str.toUpperCase();
document.write(result); // Prints: HELLO WORLD!

Likewise, you can use the toLowerCase() method to transform a string into lowercase, as demonstrated below:

var str = "Hello World!";
var result = str.toLowerCase();
document.write(result); // Prints: hello world!

Merging Two or More Strings Together

You can merge or join two or more strings using the + and += assignment operators.

var hello = "Hello";
var world = "World";
var greet = hello + " " + world;
document.write(greet); // Prints: Hello World

var wish  = "Happy";
wish += " New Year";
document.write(wish); // Prints: Happy New Year

JavaScript also offers the concat() method for combining strings, but it's not recommended.


Retrieving Individual Characters from a String

You can utilize the charAt() method to retrieve individual characters from a string, like str.charAt(index). The specified index should be an integer ranging from 0 to str.length - 1. If no index is provided, the method returns the first character in the string, as the default index is 0.

var str = "Hello World!";
document.write(str.charAt());  // Prints: H
document.write(str.charAt(6)); // Prints: W
document.write(str.charAt(30)); // Prints nothing
document.write(str.charAt(str.length - 1)); // Prints: !

There's an even better way to accomplish this. Since ECMAScript 5, strings can be treated as read-only arrays, allowing you to access individual characters using square brackets ([]) instead of the charAt() method, as shown in the following example:

var str = "Hello World!";
document.write(str[0]); // Prints: H
document.write(str[6]); // Prints: W
document.write(str[str.length - 1]); // Prints: !
document.write(str[30]); // Prints: undefined

 

Note: The only difference between accessing the character from a string using the charAt() and square bracket ([]) is that if no character is found, [] returns undefined, whereas the charAt() method returns an empty string.


Splitting a String into an Array

The split() method can break a string into an array of strings, using the syntax str.split(separator, limit). The separator argument determines where each split occurs, while the limit argument specifies the maximum length of the array.

If the separator argument is omitted or not found in the specified string, the entire string is assigned to the first element of the array. The example below demonstrates its functionality:

var fruitsStr = "Apple, Banana, Mango, Orange, Papaya";
var fruitsArr = fruitsStr.split(", ");
document.write(fruitsArr[0]); // Prints: Apple
document.write(fruitsArr[2]); // Prints: Mango
document.write(fruitsArr[fruitsArr.length - 1]); // Prints: Papaya

// Loop through all the elements of the fruits array 
for(var i in fruitsArr) {  
document.write("<p>" + fruitsArr[i] + "</p>");
}

To convert/split a string into an array of characters, you can use an empty string ("") as the separator.

var str = "INTERSTELLAR";
var strArr = str.split("");
document.write(strArr[0]); // Prints: I
document.write(strArr[1]); // Prints: N
document.write(strArr[strArr.length - 1]); // Prints: R

// Loop through all the elements of the characters array and print them
for(var i in strArr) {  
document.write("<br>" + strArr[i]);
}

You'll explore looping statements extensively in the JavaScript loops chapter.