JavaScript strings come with powerful features that make text handling flexible and efficient. Understanding these facts can help you write cleaner, faster, and more optimized code.
- Strings are immutable, meaning they cannot be changed once created.
- They support many built-in methods like slice(), replace(), and includes().
- Template literals allow easy string interpolation using backticks.
Properties of JavaScript Strings
Strings are Immutable
In JavaScript, strings are immutable, which means once you create a string, you cannot change its characters individually. Any operation that appears to modify a string, like replace() or concat(), actually creates a new string.
let s = "hello";
s[0] = "H"; // Won't work
console.log(s); // Still "hello"
Using Template Literals
Template literals, introduced in ES6, allow for writing expressions directly into strings using backticks ` and ${} syntax.
let s1 = "Sourav";
let s2 = `Hi, ${a}!`;
console.log(s2);
String Comparison
JavaScript compares strings letter by letter. This makes JavaScript strings different from some languages that use locale-based comparisons.
console.log("apple" > "banana");
Strings as Arrays of Characters
We can access JavaScript strings just like as in JavScript Arrays to get the individual character.
let s = "hello";
console.log(s[1]);
String Methods Create Copies
When you call a method like toUpperCase() or slice(), it returns a modified copy of the original string. The original string remains unaffected.
let s1 = "hello";
let s2 = s1.toUpperCase();
console.log(s2);
console.log(s1);
Splitting and Joining Strings
The split() method allows you to break a string into an array, and join() does the opposite by joining elements of an array into a single string.
let s1 = "apple,banana";
let s2 = s1.split(",");
console.log(s2);
console.log(s2.join(" & "));
Add Padding with padStart() and padEnd()
ES2017 introduced padStart() and padEnd() by which we can add padding characters to the beginning or end.
let s = "5";
console.log(s.padStart(3, "0"));
console.log(s.padEnd(3, "-"));
Reversing a String
Although JavaScript doesn’t have a built-in reverse method for strings, you can reverse a string by combining split(), reverse(), and join() methods.
let s1 = "hello";
let s2 = s1.split("").reverse().join("");
console.log(s2);
String Length as a Property
Unlike arrays, you can get the length of a string directly with .length.
let s = "hello";
console.log(s.length);
Working with Multi-Line Strings
Template literals allow to write multi-line strings without using escape characters (\n).
let s = `Roses are red,
Violets are blue,
JavaScript is fun,
And so are you!`;
console.log(s);
Check for Substrings Easily
JavaScript provides includes(), startsWith(), and endsWith() methods, which makes easy to check substrings.
let s = "JavaScript is great";
console.log(s.includes("JavaScript"));
console.log(s.startsWith("Java"));
console.log(s.endsWith("great"));