JavaScript String

JavaScript String is a series of zero or more characters, represented by using single or double-quotes.

There are two ways to create a string:

Escape Sequence

As strings are written in double or single quotes so if there is a need to show your strings in double/single quotes as output use backslash \’ \” with double/single quotes in your string. Use \\ for a backslash in string output. As shown in the following output:

<html>
<body>

<p id="tacode"></p>

<script>
var x = "JS Strings stores series of character like \"Albert Robert\"\\ Robert.";
document.getElementById("tacode").innerHTML = x; 
</script>

</body>
</html>

Output:

JavaScript String

Below table shows the JavaScript Strings escape characters and their results:

CodeResult
\bBackspace
\fForm Feed
\nNew Line
\’Single Quote
\tDouble Quote
\vBackslash

Breaking Long code lines

We avoid reading long lines of code for better readability, JavaScript String may not fit in only one line so the best way to break it is after an operator. As you can see in the below example:

<html>
<body>

<p id="tacode"></p>

<script>
document.getElementById("tacode").innerHTML =
"Hi Robert!";
</script>

</body>
</html>

Output:

JavaScript String

We can use a backslash within a string text to break the code line, the output will be the same such as:

<html>
<body>

<p id="tacode"></p>

<script>
document.getElementById("tacode").innerHTML = "Hi \
Robert!";
</script>

</body>
</html>

Output:

JavaScript String

We cannot break a code line with a backslash \ before double/single quotes

Note: As the best and safe way to break code line is by using the addition operator + within the string.

Strings can be Objects

JavaScript Strings are primitive values but we can also use strings as objects by using the keyword new. Let’s have an example:

<html>
<body>

<p id="tacode"></p>

<script>
var a = "Robert";       
var b = new String("Robert");

document.getElementById("tacode").innerHTML =
typeof a + "<br>" + typeof b;
</script>
</body>
</html>

Output:

JavaScript String