HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Strings

JavaScript strings are used to store and manipulate text. A string is simply a sequence of characters, like "Hello World", wrapped inside quotes.


Creating Strings

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

Quotes Inside Strings

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

The length Property

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

Escape Characters

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

Other Common Escape Sequences:

  • \n — New Line
  • \t — Horizontal Tab
  • \b — Backspace
let text = "We are the \"Vikings\" from the north.";
console.log(text); // We are the "Vikings" from the north.

Strings as Objects

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
Warning: Recomended way is to create strings as primitives. Defining a string as an object slows down execution speed and can produce unexpected results when comparing values.

Key Points to Remember

  • Strings are used for for storing text values
  • Wrapped in single (') or double (") quotes
  • Use the length property to count characters
  • Use the backslash (\) to escape special characters
  • Avoid using new String() for better performance