JavaScript Strings

A string is a collection of characters, numbers, special characters or a collection of all. You can enclose strings in single quotes (') or double quotes (").

Example:

.js
var myString = 'Welcome'; // Single quoted string
var myString = "Welcome!"; // Double quoted string

JavaScript allows you to use quotes in a string, until they aren’t similar to the quotes around the string.

 Example:

.js
var string1 = "Welcome";

var string2 = 'Welcome to "JavaScript"';

var string3 = 'Hi, how are you?"; // Syntax error -

Also, you can use single quotes in a single quoted string or double quotes in a double quoted string by using the backslash character (\) (escape quotes). Here the (\) is an escape character and sequences \' and \" used below are known as escape sequences.

Example:

.js
var str1 = 'I\'m fine';

var str2 = "He said \"Welcome\"";

var str3 = 'She replied \'Calm down, please\'';

JavaScript Escape Sequences: When you want to use characters that you cannot type using a keyboard, escape sequences prove helpful.

Some escape sequences are mentioned below:

Newline character replaces \n

Tab character replaced \t

Carriage-return character replaces \r

Backspace character replaces \b

Single backslash (\) replaces \\

How can you carry out operations on Strings?

JavaScript allows you to carry out different types of operations on strings using properties and methods.

Generally, objects have properties and methods only. However, the primitive data types in JavaScript can work as objects when you use them with the property access notation (dot notation).

The JavaScript interpreter helps you create temporary wrapper objects for primitive data types.

Finding the length of a String:

The length property helps you get the length of a string. It returns the number of characters (special characters as well) present in a string.

Example:

.js
var string1 = "Welcome!.";

document.write(str1.length); // Prints 8

var string2 = "Introduction 
 to JavaScript";

document.write(str2.length); // Prints 28, because 
 is only one character

Note: Remember, you don’t need to use parentheses after the str.length( ) as it is not a function. It is a property.

Locating a String Inside Another String: The indexOf( ) method helps you locate a string or a substring in another string. It gives you the position of the first existence of the string in the specified string. All the characters in a string are indexed from left to right.

Example:

.js
var str = "To be, or not to be, that is the question.";

var pos = str.indexOf("be");

document.write(pos); // 0utputs: 3

The lastIndexOf( ) helps you extract the position of the last occurrence of the particular string in the string.

Example:

.js
var str = "To be, or not to be, that is the question.";
var pos = str.lastIndexOf("be");
document.write(pos); // 0utputs: 17

The indexOf( ) and lastIndexOf( ) methods return -1 when the specified substring is not located. You can also specify the optional integer parameter that helps you set the position where you want to start the search in a string.

Example:

.js
var str = "To be, or not to be, that is the question.";

// Searching forwards

var pos1 = str.indexOf("be", 1);

document.write(pos1 + "<br>"); // 0utputs: 3

// Searching backwards

var pos2 = str.lastIndexOf("be", 1);

document.write(pos2); // 0utputs: -1

Searching for a Pattern Inside a String: The search( ) method helps you search a specific section of text or pattern in a string.

When the search( ) method finds a match, it returns the index of the first match. However, if it doesn’t find a match, it returns -1.

Example:

.js
var str = "Next time there won't be a next time.";

// Case sensitive search

var pos1 = str.search("next");

document.write(pos1 + "<br>"); // 0utputs: 27

// Case insensitive search using regexp

var pos2 = str.search(/next/i);
document.write(pos2); // 0utputs: 0

Tip: The global searches are not supported by the search method.

Taking out a Substring from a String: The slice( ) method helps you extract a section of substring from a string. You need to specify two parameters – start index and end index. The start index specifies the position where you want to start the extraction while the end index specifies the position where you want to stop the extraction.

Example:

.js
var str = "Next time there won't be a next time.";

var subStr = str.slice(5, 21);

document.write(subStr); // Prints: time there won't

JavaScript allows you to set negative values to extract the substring. It considers the negative value as strLength + startIndex. The strLength refers to the string length.

However, if the startIndex is equal or larger than the string length, the slice( ) method gives back an empty string. And, if you forgot to specify the endIndex, the slice( ) extracts the string to the end.

Example:

.js
var str = "Next time there won't be a next time.";

document.write(str.slice(-21, -10) + "<br>"); // Prints: won't be a

document.write(str.slice(27)); // Prints: next time

The substring( ) method allows you to extract a part of the specified string depending on the starting and ending indexes.

Example:

.js
var str = "Next time there won't be a next time.";

document.write(str.substring(9, 21) + "<br>"); // Prints: there won't

document.write(str.substring(10, 0) + "<br>"); // Prints: Next time

document.write(str.substring(-25, -19) + "<br>"); // Prints nothing

document.write(str.substring(25)); // Prints: a next time.

Difference between substring( ) and slice( )

  • When the argument is NaN or less than 0, substring( ) method is considered as 0.
  • When the argument is bigger than str.length, it is considered as str.length.
  • When startIndex is bigger than endIndex, then substring() will exchange those two arguments; for example, str.substring(10, 0) == str.substring(0, 10).

Extracting a Fixed Number of Characters from a String: The substr( ) methods allows you to extract a specific number of characters from a string. You need to specify the number of characters you want to extract, such as str.substr(startIndex, length).

When you set 0 or a negative number in the length, it returns an empty string.

Example:

.js
var str = "Next time there won't be a next time.";

document.write(str.substring(9, 21) + "<br>"); // Prints: there won't

document.write(str.substring(10, 0) + "<br>"); // Prints: Next time

document.write(str.substring(-25, -19) + "<br>"); // Prints nothing

document.write(str.substring(25)); // Prints: a next time.

Replacing the Contents of a String: The replace( ) method helps you replace a section of a string with any other string. The original string is not impacted as it returns a new string.

Example:

.js
var str = "Next time there won't be a next time.";

var result = str.replace("won't", "will");

document.write(result); // 0utputs: Next time there will be a next time.

The replace( ) method is case-sensitive and replaces the first instance that it encounters.

Here’s how you can replace the substring in a case-insensitive manner.

.js
var str = "We love Cricket.";
var result = str.replace(/we/i, "I");

document.write(result); // 0utputs: I love Cricket.

To replace all the instances of a specific substring in a string (in a case-insensitive manner), consider using the g modifier together with the i modifier.

Example:

.js
var str = "Modify your attitude to modify yourselves.";

var result = str.replace(/modify/ig, "change");

document.write(result); // 0utputs: change your attitude to change yourselves.

Changing a String to Uppercase or Lowercase: The toUpperCase( ) method allows you to change a string to uppercase.

Example:

.js
var str = "Introduction to JavaScript!";

var result = str.toUpperCase();

document.write(result); // Prints: INTRODUCTION TO JAVASCRIPT!

 

The toLowerCase( ) helps you change a string to lowercase.

Example:

.js
var str = "Introduction to JavaScript!";

var result = str.toLowerCase();

document.write(result); // Prints: introduction to javascript!

Concatenating Two or More Strings: The + and += assignment operators are used to concatenate two or more strings.

Example:

.js
var str1 = "Welcome to";

var str2 = "JavaScript";

var str3 = str1 + " " + str2;

document.write(str3); // Prints: Welcome to JavaScript

Retrieving Single Characters from a String: The charAt( ) method allows you to retrieve single characters from a string. You need to specify the index in the range 0 and str.length -1. When you don’t specify any index, it returns the first character in the string.

Example:

.js
var str = "Welcome to JavaScript!";
document.write(str.charAt() + "<br>"); // Prints: W
document.write(str.charAt(9) + "<br>"); // Prints: o
document.write(str.charAt(22) + "<br>"); // Prints nothing
document.write(str.charAt(str.length - 4)); // Prints: i

JavaScript offers another way to access individual characters. Use the square brackets [ ] to access the characters.

Example:

.js
var str = "Welcome to JavaScript!";
document.write(str[0] + "<br>"); // Prints: W
document.write(str[11] + "<br>"); // Prints: J
document.write(str[str.length - 3] + "<br>"); // Prints: p
document.write(str[50]); // Prints: undefined

What is the difference between the two methods?

When no character is found, the square brackets[] return undefined while the charAt( ) method returns an empty string.

Splitting a String into an Array: The split( ) method helps you split the string into an array.

Example:

.js
var courseStr = "English, Maths, EVS, Computer, Hindi";
var courseArr = courseStr.split(", ");
document.write(courseArr[0] + "<br>"); // Prints: English
document.write(courseArr[2] + "<br>"); // Prints: EVS
document.write(courseArr[courseArr.length - 1]); // Prints: Hindi
document.write("<hr>");

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

To break down a string into array of characters, follow the below example:

.js
var str = "JAVASCRIPT";
var strArr = str.split("");
document.write(strArr[0] + "<br>"); // Prints: J
document.write(strArr[1] + "<br>"); // Prints: A
document.write(strArr[strArr.length - 1]); // Prints: T
document.write("<hr>");

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