JavaScript Strings

JavaScript strings store text. You can write them with single quotes, double quotes or backticks. Strings are immutable: string methods always return a new string and leave the original unchanged.

Template Literals

Backtick strings (template literals) can span multiple lines and embed any expression with the dollar-brace syntax. They are the modern way to build strings.

const item = "Coffee";
const price = 4.5;
const qty = 3;
console.log(`${qty} x ${item} = ${(price * qty).toFixed(2)}`);

const multi = `Line one
Line two`;
console.log(multi);
3 x Coffee = $13.50
Line one
Line two

Length and Characters

length gives the number of characters. Access characters with brackets or at(), which also accepts negative indexes to count from the end.

const word = "JavaScript";
console.log(word.length);
console.log(word[0], word.at(-1));
console.log(word.slice(0, 4), word.slice(4));
10
J t
Java Script

Searching in Strings

includes, startsWith and endsWith return booleans. indexOf returns the position of the first match or -1.

const msg = "Learn JavaScript on naeemamin.cloud";
console.log(msg.includes("Script"));
console.log(msg.startsWith("Learn"), msg.endsWith(".cloud"));
console.log(msg.indexOf("on"));
console.log(msg.indexOf("Python")); // -1 means not found
true
true true
17
-1

Transforming Strings

Common methods change case, remove whitespace, replace text, split into arrays and pad to a fixed width.

const raw = "  hello world  ";
console.log("[" + raw.trim() + "]");
console.log(raw.trim().toUpperCase());
console.log("a-b-c".replaceAll("-", "+"));
console.log("red,green,blue".split(",").length);
console.log("7".padStart(3, "0"));
console.log("ha".repeat(3));
[hello world]
HELLO WORLD
a+b+c
3
007
hahaha

Escape Characters

  • \n new line
  • \t tab
  • \' and \" quotes inside strings
  • \\ a literal backslash
  • Inside template literals, use \` for a backtick

Frequently asked questions

What is the difference between single quotes, double quotes and backticks?

Single and double quotes behave the same. Backticks create template literals, which support embedded expressions and multi-line text.

How do I convert a string to a number in JavaScript?

Use Number("42"), parseInt("42", 10) or parseFloat("3.14"). Number returns NaN if the whole string is not numeric.

Why does my string method not change the string?

Strings are immutable. Methods return a new string, so assign the result: name = name.trim().