JavaScript Strings

A string is text. Write it inside single quotes, double quotes or backticks.

let a = "Hello";
let b = 'World';
let c = `Hello World`;
console.log(a + " " + b);
Output of the above program is

Hello World


Template literals

Backticks allow a variable or any expression inside ${ }, and strings on many lines.

let name = "Robin";
let age = 25;
console.log(`Name: ${name}, next year age: ${age + 1}`);
Output of the above program is

Name: Robin, next year age: 26


Common string methods

Strings cannot be changed. Every method returns a new string.

let s = "Hello, World";

console.log(s.length);
console.log(s.toUpperCase());
console.log(s.toLowerCase());
console.log(s.slice(0, 5));
console.log(s.indexOf("World"));
console.log(s.replace("World", "JS"));
console.log(s.split(", "));
console.log(s.includes("lo"));
console.log(s.startsWith("Hello"));
console.log("  hi  ".trim());
console.log("ab".repeat(3));
console.log("5".padStart(3, "0"));
Output of the above program is

12
HELLO, WORLD
hello, world
Hello
7
Hello, JS
[ "Hello", "World" ]
true
true
hi
ababab
005

MethodUse
lengthNumber of characters (a property, no brackets)
slice(start, end)A part of the string
indexOf(text)Position of the text, or -1
replace(old, new)Replaces the first match
split(sep)Breaks into an array
includes(), startsWith(), endsWith()Checks
trim()Removes spaces at both ends
repeat(n), padStart()Repeat and pad

Characters by position

let word = "JavaScript";
console.log(word[0]);
console.log(word.at(-1));
Output of the above program is

J
t

at(-1) gives the last character.


Escape characters

console.log("She said \"Hi\"");
console.log("Line 1\nLine 2");
Output of the above program is

She said "Hi"
Line 1
Line 2


Summary

  • Use backticks and ${ } to put values in strings.
  • String methods return new strings.
  • Next: Numbers and Math.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.