JavaScript Strings
A string is a piece of text, written inside quotes.
Creating Strings
Example
let city = "Karachi";
let area = 'Gulshan-e-Iqbal';
let line = `I live in ${area}, ${city}.`;
console.log(line);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
<!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 »2 x Shalwar Kameez = Rs 6400
String Length
The length property counts the characters, including spaces:
Example
let name = "Ali Raza";
console.log(name.length); // 8Escape Characters
To use a quote of the same kind inside a string, put a backslash \ before it.
| Code | Gives |
|---|---|
\" | Double quote |
\' | Single quote |
\\ | Backslash |
\n | New line |
Example
let msg = "She said \"Shukriya\" and left.";
console.log(msg);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.
| Method | What 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
<!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 »AYESHA KHAN ayesha true ayesha malik 0300,1234567 007
Characters by Position
Positions (indexes) start at 0. at(-1) gives the last character.
Example
let word = "Pakistan";
console.log(word[0]); // P
console.log(word.at(-1)); // nStrings 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?
