A string is a sequence of characters used to represent text. It is one of the primitive data types in JavaScript. Strings are immutable, which means once a string is created, it cannot be changed. String methods don't change the original string; they return a new one.
Strings can be created using single quotes (''), double quotes (""), or backticks
(``).
// Using double and single quotes
let singleQuote = 'Hello';
let doubleQuote = "World";
// Template Literals (ES6) with backticks
let name = "Ragini";
let greeting = `Hello, ${name}!`; // Allows embedding variables
document.write(greeting);
JavaScript provides a rich set of methods to manipulate strings.
The length property returns the number of characters in a string.
let text = "Hello World";
document.write(text.length); // 11
Extracts a part of a string and returns it as a new string. The end index is not included.
Negative indices can be used to count from the end.
let text = "JavaScript";
document.write(text.slice(0, 4)); // "Java"
document.write(text.slice(4)); // "Script"
document.write(text.slice(-3)); // "ipt"
These methods convert a string to uppercase or lowercase, respectively.
let msg = "Hello World";
document.write(msg.toUpperCase()); // "HELLO WORLD"
document.write(msg.toLowerCase()); // "hello world"
Replaces the first occurrence of a specified value with another value. To replace all
occurrences, use replaceAll() or a regular expression with the global flag.
let text = "I love Java, because Java is great.";
document.write(text.replace("Java", "JavaScript")); // "I love JavaScript, because Java is great."
document.write(text.replaceAll("Java", "JavaScript")); // "I love JavaScript, because JavaScript is great."
Removes whitespace from both ends of a string. trimStart() and trimEnd() remove
whitespace from the beginning or end only.
let text = " Hello World ";
document.write(text.trim()); // "Hello World"
Splits a string into an array of substrings based on a specified separator.
let text = "HTML,CSS,JS";
let skills = text.split(",");
document.write(skills); // ["HTML", "CSS", "JS"]
Checks if a string contains a specified value. It returns true or false and is
case-sensitive.
let text = "JavaScript is awesome";
document.write(text.includes("Script")); // true
document.write(text.includes("script")); // false
| Feature | Array | String |
|---|---|---|
| Type | Object (Non-Primitive) | Primitive |
| Mutability | Mutable (can be changed) | Immutable (cannot be changed) |
| Stores | Elements of any type | A sequence of characters |
| Example | [1, "hi", true] |
"Hello World" |
Test your understanding of JavaScript Strings.
let str = "javascript";let text = "Hello World";slice() method to extract the word "World".let sentence = "I like apples.";replace() method to change "apples" to "oranges".let data = "one,two,three";split() method with a comma "," as the separator.