Javascript String : Complete Guide


In this tutorial, you are going to learn about string in javascript, different ways to create it, its use, and some of the methods available to manipulate it.

Javascript String

Javascript string is a sequence of characters. It can be used to represent text, numbers, and other information. Example "Hello World", "1234", "true", "null", etc.

In HTML, it is also used to store the value of an element's attribute. For example, the src attribute of an img element can be used to store the URL of the image.

Creating a string

A string can be created by using string literals or by using a String() constructor.

# String literal

It is the simplest way to create a string. Enclose the text content in single quotes ('), double quotes ("), or backticks (`).

Single quote - 'Hello World'

Double quote - "Hello World"

Backticks - `Hello World`

Example

// String literal
// Single quotes
var str1 = 'Hello World';
console.log(str1);

// Double quotes
var str2 = "Hello World";
console.log(str2);

// Backticks
var str3 = `Hello World`;
console.log(str3);

// Checking the type of variable
console.log(typeof str1, typeof str2, typeof str3);
Try It

# String constructor

It is also possible to create a string object using the String() constructor. It is used to create a string object. It takes one argument, which is converted to a string.

Example

// String constructor
// String object
var str = String('Hello World');

console.log(str);

// Checking the type of variable
console.log(typeof str);
Try It

Javascript String Format

String formatting is a way to format a string using placeholders. It is used to insert values into a string.

Backticks allow us to format a string and embed any javascript expression into the javascript string, by wrapping it in ${...}.

Expression inside ${...} will be evaluated and output will be returned. Example : `1 + 1 = ${1+1}` will output '1 + 1 = 2'.

Example: JavaScript Expressions

// expression within backticks
var valueOfPI = `Value of PI = ${Math.PI}.`;
console.log(valueOfPI);

var sum = `10 + 15 = ${10 + 15}`;
console.log(sum);

var multiplication = `20 * 12 = ${20 * 12}`;
console.log(multiplication);
Try It

Not only mathematical expression can be used in backticks, but also variables, functions, and any valid javascript expression can be used.

Example

// variable in backticks
var name = 'John';
var greeting = `Hello ${name}`;
console.log(greeting);

var age = 30;
console.log(`${name} is ${age > 40 ? 'old' : 'young'}`);

Multiline String

A multiline string is a string that spans multiple lines.

The easiest way to create a multiline string is by using backticks.

Example

var webStack = `Languages:
  * HTML
  * CSS
  * Javascript`;
console.log(webStack);
Try It

You can also use quotes to create a multi-line string by adding \ (backslash) before the line break.

Example

var webStack = "Languages: \
  * HTML \
  * CSS \
  * Javascript";

console.log(webStack);

Length Of String In Javascript

In javascript, String has many properties and predefined methods. We will learn about string methods in the coming chapter.

To get the length of a string we have a property called length. It returns the number of characters in the string.

Example

var alphabets = "abcdefghijklmnopqrstuvwxyz";

// using length property
var length1 = alphabets.length; // output: 26
console.log(length1);

// Multi line String
var multiLine = `
  Hello
  World`;

var length2 = multiLine.length; // output: 16
console.log(length2); // 10 charaters, 4 spaces and 2 new lines
Try It

Accessing characters in string

To access a character in a string, you can use square bracket notation just like an array. The index of the character is the position of the character in the string. The first character has index 0, the second character has index 1, and so on.

Example

var alphabets = "abcdefghijklmnopqrstuvwxyz";

// accessing characters
var char1 = alphabets[0]; // output: 'a'
console.log(char1);

var char2 = alphabets[1]; // output: 'b'
console.log(char2);

var last = alphabets[alphabets.length - 1]; // output: 'z'
console.log(last);

Javascript String Concatenation

Concatenation is the addition of 2 or more strings into a single string.

In javascript, String can be concatenated using the + operator between two different strings.

Example

var str1 = "Hello ";
var str2 = "world";

// concatenation
var result = str1 + str2; // Hello world

// Output
console.log(result);
Try It

When you want to assemble a string at different stages of the program into a single string then you can use the += operator.

Example

var alphabets = '';
for (var i = 0; i < 26; i++) {
  alphabets += String.fromCharCode(i + 65);
}

// Output
console.log(alphabets);

Escape Character in Javascript

Sometimes you need to show quotes (" or ') in texts but when you write extra quotes in the string then Javascript gets confused for where the string ends.

See the example below, we want the "ocean" to be in double quotes.

"Color of "ocean" is Blue."

The above string will be chopped at "Color of ". And will also cause an error Uncaught SyntaxError: unexpected token: identifier, because javascript identifies string end at 2nd occurrence of the double quote and the next character becomes meaningless for it.

To solve the above problem we need to escape quotes using the backslash escape character ( \ ) in the string.

Example

var ocean = "Color of \"ocean\" is Blue.";
  
// Output
console.log(ocean);
Try It

Backslash character ( \ ) is an escape character that is used to escape the character which has a special meaning, like a single quote, double quote, backtick, etc.

In the above example, we have used the backslash character to escape the double quote character ( \" ) and the out contains double quotes.

To Display Write Output
double quote ( " ) \" "
single quote ( ' ) \' '
backslash ( \ ) \\ \

The code \' escape single quote.

Example

var sentence =  'Escaping 'single quotes'.';
console.log(sentence);
Try It

To escape the backslash itself, write 2 backslashes together (\\).

Example

var sentence =  "This is how to display backslash \\ itself";
console.log(sentence);
Try It

Here are more commonly used escape characters in javascript:

Character Description
\n New Line (used in the string to create a new line)
\t Horizontal Tab (used in the string to create a tab)
\b backspace
\f form feed
\v Verticle tab
\f form feed
\xXX Unicode character. Example: \x23
\uXXXX A Unicode symbol. Example: \u00A5

Newline (\n) is an escape character is used to create a new line in the string.

Example

var webStack = `Languages: \n* HTML  \n* CSS  \n* Javascript`;
console.log(webStack);

Using backslash in unicode characters.

Example

var a = "\x23";
var b = "\u00A5";
console.log(a);
console.log(b);
Try It

JavaScript String Methods

JavaScript string methods are used to manipulate strings. There are many methods available in JavaScript string methods. Some of the important methods are listed below:

Method Description
charAt() Returns the character at the specified index (position) of a string.
indexOf() Returns the position of the first found occurrence of a specified value in a string.
lastIndexOf() Returns the position of the last found occurrence of a specified value in a string.
match() Used to match a string with a regular expression and returns an array containing the matches, or null if no match is found.
replace() Finds a match between a string and a regular expression, and returns a new string with the matches replaced.
search() Searches a string for a specified value and returns the position of the match.
slice() Extracts a part of a string and returns a new string.
split() Splits a string into an array of substrings.
substring() Extracts the characters from a string, beginning at a specified start position, and through an end position.

Points to remember:

  1. Javascript string is used to store textual values.
  2. You can use a single quote, double quote, and backticks to create a string.
  3. There are 2 ways to create a string: string literal and String Constructor.
  4. Backslash \ is used as an escape character.
  5. Use the length property to find the length of the string.