JavaScript Tutorial menu

JavaScript Strings

A string is a piece of text, written inside quotes.

Creating Strings

Example

javascript
let city = "Karachi";
let area = 'Gulshan-e-Iqbal';
let line = `I live in ${area}, ${city}.`;
console.log(line);
Output
I live in Gulshan-e-Iqbal, Karachi.

Template Literals

Strings in backticks are called template literals. They have two big advantages:

  • You can put a value inside with ${ }, instead of joining with +
  • The string can go over several lines

Example

html
<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
const item = "Shalwar Kameez";
const price = 3200;
const qty = 2;
document.getElementById("demo").innerHTML = `${qty} x ${item} = Rs ${price * qty}`;
</script>

</body>
</html>
Try it Yourself »
Output
2 x Shalwar Kameez = Rs 6400

String Length

The length property counts the characters, including spaces:

Example

javascript
let name = "Ali Raza";
console.log(name.length);   // 8

Escape Characters

To use a quote of the same kind inside a string, put a backslash \ before it.

CodeGives
\"Double quote
\'Single quote
\\Backslash
\nNew line

Example

javascript
let msg = "She said \"Shukriya\" and left.";
console.log(msg);
Output
She said "Shukriya" and left.

Useful String Methods

Strings have many built-in methods. They never change the original string; they return a new one.

MethodWhat it does
toUpperCase() / toLowerCase()Change the case
trim()Remove spaces from both ends
slice(start, end)Cut out part of the string
includes(text)True if the text is found
indexOf(text)Position of the text, or -1
replace(a, b)Replace the first a with b
replaceAll(a, b)Replace every a with b
split(separator)Break into an array
startsWith() / endsWith()Check the start or end
padStart(n, char)Pad to a length from the left

Example

html
<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
let input = "   ayesha khan   ";
let clean = input.trim();
let lines = [
  clean.toUpperCase(),
  clean.slice(0, 6),
  clean.includes("khan"),
  clean.replace("khan", "malik"),
  "0300-1234567".split("-"),
  "7".padStart(3, "0")
];
document.getElementById("demo").innerHTML = lines.join("<br>");
</script>

</body>
</html>
Try it Yourself »
Output
AYESHA KHAN
ayesha
true
ayesha malik
0300,1234567
007

Characters by Position

Positions (indexes) start at 0. at(-1) gives the last character.

Example

javascript
let word = "Pakistan";
console.log(word[0]);      // P
console.log(word.at(-1));  // n

Strings are immutable: you cannot change one character in place. word[0] = "p" does nothing. Create a new string instead, for example with replace() or slice().

Exercise

Exercise

What does "Karachi".slice(0, 4) return?

Learn JavaScript with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp