JavaScript Strings JAVASCRIPT

JavaScript Strings  

JavaScript Strings

JavaScript Strings

A JavaScript string is zero or more characters written inside quotes. You can use single or double quotes:

var carName1 = "Volvo XC60";  // Double quotes
var carName2 = 'Volvo XC60';  // Single quotes

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

var answer1 = "It's alright";
var answer2 = "He is called 'Deepak'";
var answer3 = 'He is called "Deepak"';

String Length

To find the length of a string, use the built-in length property:

 

Example

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;

Escape Character

Because strings must be written within quotes, JavaScript will misunderstand this string:

var x = "We are the so-called "Vikings" from the north.";

The string will be chopped to "We are the so-called ".

The solution to avoid this problem is to use the backslash escape character.

The backslash (\) escape character turns special characters into string characters:

Code Result Description
\' ' Single quote
\" " Double quote
\\ \ Backslash

The sequence \"  inserts a double quote or single quote in a string:

 

 

Example

The sequence \"  inserts a double quote in a string:

var x = "We are the so-called \"Vikings\" from the north.";

The sequence \'  inserts a single quote in a string:

var x = 'It\'s alright.';

The sequence \\  inserts a backslash in a string:

var x = "The character \\ is called backslash.";

Download free E-book of JAVASCRIPT


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries