Javascript strings are the collection of a finite number of characters that are wrapped inside single quote''
, double quote" "
or back tik` `
.
Strings can store textual contents as well as form fields values such as input, select, textarea, etc.
In Javascript, a similar string can be put either in a single quote or double quote. Let us understand it with the help of an example.
Source Code
var x = "hello javascript string";
var y = 'hello javascript string';
Code Explanation
Please keep in mind that, there is no difference in the above-declared string.
In javascript string, backslash, i.e. is used to escape the character. Let us understand it with the help of an example.
Source Code
var x = " Smith's car is really one of the best cars in the market.";
Javascript string can be declared in the followings ways:
1.0
Using Single Quote''
2.0
Using Double Quote" "
3.0
Using Back Tick``
Let us understand it with the help of an example.
Source Code
var userName='Smith';
var cityName="Surat";
var job = `Web designer and developer`;
ES6 introduced template literals for declaring string using back tik ``
.
Source Code
var str=`Learn javascript`;
String interpolation is a process of inserting a variable inside the template literal using ${variable}. Let us understand it with the help of an example.
Source Code
var name = "John Doe";
var job = "designer";
console.log(`Hello ,my name is ${name} and i am a ${job}`); //ES6
console.log("Hello, my name is " + name + " and i am a " + job); //ES5
Javascript multi-line string can be declared using template literal. You can do the same thing in es5 using the + operator.
Source Code
var template=`I am a developer
as well as designer
and working in the mnc.
`;
Javascript string can be accessed using the followings ways:
Since strings are the array hence it will be accessed by:
Source Code
const x = 'hello javascript';
console.log(x[4]); // "0"
Javascript string is accessed by other methods such as charAt().For example.
Source Code
const x = "hello javascript";
console.log(x.charAt(1)); // "e"