JAVASCRIPT BASIC
JAVASCRIPT & DOM
JAVASCRIPT & BOM
JAVASCRIPT ADVANCED
JAVASCRIPT EXAMPLES
JAVASCRIPT REFERENCE
Advertisements

JavaScript Strings

In this tutorial you will learn how to create and manipulate strings in JavaScript.

What is String in JavaScript

A string is a sequence of letters, numbers, special characters and arithmetic values or combination of all. Strings can be created by enclosing the string literal (i.e. string characters) either within single quotes (') or double quotes ("), as shown in the example below:

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

You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

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

However, you can still use single quotes inside a single quoted strings or double quotes inside double quoted strings by escaping the quotes with a backslash character (\), like this:

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

The backslash (\) is called an escape character, whereas the sequences \' and \" that we've used in the example above are called escape sequences.


JavaScript Escape Sequences

Escape sequences are also useful for situations where you want to use characters that can't be typed using a keyboard. Here are some other most commonly used escape sequences.

  • \n is replaced by the newline character
  • \t is replaced by the tab character
  • \r is replaced by the carriage-return character
  • \b is replaced by the backspace character
  • \\ is replaced by a single backslash (\)

Here's an example to clarify the how escape sequences actually works:

let str1 = "The quick brown fox \n jumps over the lazy dog.";
document.write("<pre>" + str1 + "</pre>"); // Create line break
 
let str2 = "C:\Users\Downloads";
document.write(str2); // Prints C:UsersDownloads
 
let str3 = "C:\\Users\\Downloads";
document.write(str3); // Prints C:\Users\Downloads

Performing Operations on Strings

JavaScript provides several properties and methods to perform operations on string values. Technically, only objects can have properties and methods. But in JavaScript primitive data types can act like objects when you refer to them with the property access notation (i.e. dot notation).

JavaScript making it possible by creating a temporary wrapper object for primitive data types. This process is done automatically by the JavaScript interpreter in the background.

Getting the Length of a String

The length property returns the length of the string, which is the number of characters contained in the string. This includes the number of special characters as well, such as \t or \n.

let str1 = "This is a paragraph of text.";
document.write(str1.length); // Prints 28
 
let 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, not a function, so don't use parentheses after it like str.length(). Instead just write str.length, otherwise it will produce an error.


Finding a String Inside Another String

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

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

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

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

Both the indexOf(), and the lastIndexOf() methods return -1 if the substring is not found. Both methods also accept an optional integer parameter which specifies the position within the string at which to start the search. Here's an example:

let str = "If the facts don't fit the theory, change the facts.";
 
// Searching forwards
let pos1 = str.indexOf("facts", 20);
alert(pos1); // 0utputs: 46
 
// Searching backwards
let pos2 = str.lastIndexOf("facts", 20);
alert(pos2); // 0utputs: 7

Note: Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character of a string called myStr is myStr.length - 1.


Searching for a Pattern Inside a String

You can use the search() method to search a particular piece of text or pattern inside a string.

Like indexOf() method the search() method also returns the index of the first match, and returns -1 if no matches were found, but unlike indexOf() method this method can also take a regular expression as its argument to provide advanced search capabilities.

let str = "Color red looks brighter than color blue.";
 
// Case sensitive search
let pos1 = str.search("color");
alert(pos1); // 0utputs: 30
 
// Case insensitive search using regexp
let pos2 = str.search(/color/i);
alert(pos2); // 0utputs: 0

Note: The search() method does not support global searches; it ignores the g flag or modifier (i.e. /pattern/g) of its regular expression argument.

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


Extracting a Substring from a String

You can use the slice() method to extract a part or substring from a string.

This method takes 2 parameters: start index (index at which to begin extraction), and an optional end index (index before which to end extraction), like str.slice(startIndex, endIndex).

The following example slices out a portion of a string from position 4 to position 15:

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

You can also specify negative values. The negative value is treated as strLength + startIndex, where strLength is the length of the string (i.e. str.length), for example, if startIndex is -5 it is treated as strLength - 5. If startIndex is greater than or equal to the length of the string, slice() method returns an empty string. Also, if optional endIndex is not specified or omitted, the slice() method extracts to the end of the string.

let 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 use the substring() method to extract a section of the given string based on start and end indexes, like str.substring(startIndex, endIndex). The substring() method is very similar to the slice() method, except few differences:

  • If either argument is less than 0 or is NaN, it is treated as 0.
  • If either argument is greater than str.length, it is 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 following example will show you how this method actuallty works:

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

Extracting a Fixed Number of Characters from a String

JavaScript also provide the substr() method which is similar to slice() with a subtle difference, the second parameter specifies the number of characters to extract instead of ending index, like str.substr(startIndex, length). If length is 0 or a negative number, an empty string is returned. The following example demonstrates how it works:

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

Replacing the Contents of a String

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

This replace() method returns a new string, it doesn't affect the original string that will remain unchanged. The following example will show you how it works:

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

By default, the replace() method replaces only the first match, and it is case-sensitive. To replace the substring within a string in a case-insensitive manner you can use a regular expression (regexp) with an i modifier, as shown in the example below:

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

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

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

Converting a String to Uppercase or Lowercase

You can use the toUpperCase() method to convert a string to uppercase, like this:

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

Similarly, you can use the toLowerCase() to convert a string to lowercase, like this:

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

Concatenating Two or More Strings

You can concatenate or combine two or more strings using the + and += assignment operators.

let hello = "Hello";
let world = "World";
let greet = hello + " " + world;
document.write(greet); // Prints: Hello World
 
let wish  = "Happy";
    wish += " New Year";
document.write(wish); // Prints: Happy New Year

JavaScript also provides concat() method to combine strings, but it is not recommended.


Accessing Individual Characters from a String

You can use the charAt() method to access individual character from a string, like str.charAt(index). The index specified should be an integer between 0 and str.length - 1. If no index is provided the first character in the string is returned, since the default is 0.

let 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 is even better way to do this. Since ECMAScript 5, strings can be treated like read-only arrays, and you can access individual characters from a string using square brackets ([]) instead of the charAt() method, as demonstrated in the following example:

let 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 be used to splits a string into an array of strings, using the syntax str.split(separator, limit). The seperator argument specifies the string at which each split should occur, whereas the limit arguments specifies the maximum length of the array.

If separator argument is omitted or not found in the specified string, the entire string is assigned to the first element of the array. The following example shows how it works:

let fruitsStr = "Apple, Banana, Mango, Orange, Papaya";
let 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(let i in fruitsArr) {  
    document.write("<p>" + fruitsArr[i] + "</p>");
}

To split a string into an array of characters, specify an empty string ("") as a separator.

let str = "INTERSTELLAR";
let 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(let i in strArr) {  
    document.write("<br>" + strArr[i]);
}

You will learn about looping statements in detail JavaScript loops chapter.

Advertisements
Bootstrap UI Design Templates