JavaScript strings are used to store and manipulate text. A string is simply a sequence of characters, like "Hello World", wrapped inside quotes.
You can create a string using either single quotes or double quotes. There is no technical difference between them — just be consistent in your project.
let name = "Mim Akter"; // Double quotes
let city = 'Dhaka'; // Single quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding the string.
let sentence1 = "It's a beautiful day"; // Single quote inside double quotes
let sentence2 = 'He said "Hello" to me'; // Double quotes inside single quotes
Every string has a built-in length property that returns the number of
characters in the string, including spaces.
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
console.log(length); // 26
Because strings must be written within quotes, JavaScript will misunderstand a string like
this: let text = "We are the "Vikings" from the north.";
To solve this, use the backslash (\) escape character. It turns special characters into string characters.
| Code | Result | Description |
|---|---|---|
\' |
' |
Single quote |
\" |
" |
Double quote |
\\ |
\ |
Backslash |
\n — New Line\t — Horizontal Tab\b — Backspacelet text = "We are the \"Vikings\" from the north.";
console.log(text); // We are the "Vikings" from the north.
Normally, JavaScript strings are primitive values. However, strings can also be defined
as objects using the new keyword.
let x = "Mim"; // x is a string
let y = new String("Mim"); // y is an object
') or double (") quoteslength property to count characters\) to escape special charactersnew String() for better performance