JavaScript String


JavaScript string is an object that represents a sequence of characters.

It is used for storing and manipulating text.

We can create JavaScript string in 2 ways:

1. By string literal
2. By string object (using new keyword)


1. By string literal

We can create a string by a string literal enclosed in quotes either single (‘’) or double (“”).

Syntax:

    var stringName = “String Value”;


Example:

    var website = “TutorialsDuniya”;



2. By string object

We can create a string by a string object using new keyword which is used to create an instance of string.

Syntax:

    var stringName = new String (“String Value”);


Example:

    var website = new String (“Tutorialsduniya”);


String Length

We can get the length of a string using it’s built in length property.

Syntax:

    stringName.length;


Example:

    var website = “Tutorialsduniya”;
    document.write(website.length); // prints15



String Concatenation

We can concatenate two strings in JavaScript using the plus (+) operator.

Syntax:

    var newString = string1 + string2;


Example:

    var website = “Tutorials” + “Duniya”; // stores TutorialsDuniya


Special Characters

We can insert a single quote inside a double quoted string or vice versa easily but if we need to insert a double quote inside a double quoted string, we have to use the backslash ( \ ) escape character.

Example:

    var website = “The website name is \”TutorialsDuniya\””; // stores The website name is “TutorialsDuniya”.