JS Strings

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

What is String in JavaScript

A string in JavaScript is a sequence or series of letters, numbers, special characters, and arithmetic values or a combination of all. In order to create strings the string literal must be enclosed (i.e. string characters) either within single quotes (') or double quotes ("), as shown in the example below:

Example:

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

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

Example:

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

However, single quotes can be used inside a single-quoted strings and double quotes can be used inside double-quoted strings by escaping the quotes with a backslash character (), like this:

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

The backslash () is called an escape character, and the escape sequences are ' and " which are already used in the example above.

 

JavaScript Escape Sequences

You can use escape sequences when you want to use characters that can't be typed using a keyboard. below are some commonly used escape sequences.

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

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

<html>
<head></head>
<body>
  <script>
  var str1 = "The quick brown fox n jumps over the lazy dog.";
document.write("<pre>" + str1 + "</pre>"); // Create line break
 
var str2 = "C:UsersDownloads";
document.write(str2); // Prints C:UsersDownloads
 
var str3 = "C:UsersDownloads";
document.write(str3); // Prints C:UsersDownloads
  </script>
</body>
</html>

Try with example


Performing Operations on Strings

Several properties and methods applied to perform operations on string values are typically provided by JavaScript. Technically, only objects can have properties and methods but primitive or primary data types can act like objects when you refer to them with the property access notation in JavaScript (i.e. dot notation)

JavaScript makes it possible by creating a temporary wrapper object for primitive or primary data types. This process is executed 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 present in the string. This includes the number of special characters as well, such as t or n.

<html>
<head></head>
<body>
  <script>
  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
  </script>
</body>
</html>

Try with example

Note: Don’t use parentheses after length like str.length() since it is a property, not a function. Instead, just write str.length, otherwise, it will produce an error.

 

Finding a String Inside Another String

To find a substring or string within another string using the indexOf() method. The index or position of the first occurrence of a specified string within a string will return if this method is applied.
Example:

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

Try with example

Likewise, 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:

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

Try with example

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

<html>
<head></head>
<body>
  <script>
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
  </script>
</body>
</html>

Try with example


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

 

Searching for a Pattern Inside a String

The search() method can be used to search a particular piece of text or pattern inside a string.

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

<html>
<head></head>
<body>
  <script>
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
  </script>
</body>
</html>

Try with example

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

In subsequent tutorials, you'll learn more about expression argument

 

Extracting a Substring from a String

The slice() method can be used to extract a part or substring from a string.

This type of method takes two parameters which are the start index ( or index for which the extraction begins), and an optional end index (or index before which to extraction end), like ‘str.slice(startIndex, endIndex).’

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

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

Try with example 

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

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 use the substring() method to extract or select a section of the given string based on start and end indexes, like str.substring(startIndex, endIndex). The substring() method shares similarities with the slice() method, yet has a few differences:

  • It is treated as 0 if either argument is less than 0 or is NaN.
  • It is treated as if it were str.length if either argument is greater than str.length.
  • Substring() will swap those two arguments if startIndex is greater than endIndex, for instance, str.substring(5, 0) == str.substring(0, 5).

The following example will show you how this method works:

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.


Extracting a Fixed Number of Characters from a String

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

Example:

<html>
<head></head>
<body>
  <script>
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.
  </script>
</body>
</html>

Try with example


Replacing the Contents of a String

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

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

Example:

<html>
<head></head>
<body>
  <script>
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.
  </script>
</body>
</html>

Try with example

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

<html>
<head></head>
<body>
  <script>
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.
  </script>
</body>
</html>

Try with example

Similarly, you can use the g modifier along with the i modifier to replace all the occurrences of a substring within a string in a case-insensitive manner, 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.

 

Converting a String to Uppercase or Lowercase

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

Example:

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

Try with example

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

Example:

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

Try with example
 

Concatenating Two or More Strings

To concatenate or combine two or more strings you can use the + and += assignment operators. 

<html>
<head></head>
<body>
  <script>
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
  </script>
</body>
</html>

Try with example

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

 

Accessing Individual Characters from a String

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

Example:

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: !

Try with example

A better way to do this is since ECMAScript 5, strings can be treated like read-only arrays. Individual characters can be accessed from a string using square brackets ([]) instead of the charAt() method, as demonstrated in the following example:

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

Try with example

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

 

Splitting a String into an Array

According to its name, the split() method is used to split a string into an array of strings by using the syntax str.split(separator, limit). The separator argument specifies the string at which each split should occur, while the limit argument specifies the maximum length of the array.

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

Example:

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>");
}

Try with example

Specify an empty string ("") as a separator to split a string into an array of characters. You will learn about looping statements in a detailed JavaScript loops tutorial.

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]);
}

Try with example