String methods help you work with and manipulate text. It is important to remember that all string methods return a new string. They do not modify the original string, as strings in JavaScript are immutable.
There are three common methods for extracting a part of a string:
Extracts a part of a string and returns the extracted part in a new string.
let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13); // Result: "Banana"
Similar to slice(), but it cannot accept negative indexes.
let str = "Hello World";
console.log(str.substring(0, 5)); // Result: "Hello"
You can easily convert a string to uppercase or lowercase using these methods:
let text = "Hello World!";
let upper = text.toUpperCase(); // "HELLO WORLD!"
let lower = text.toLowerCase(); // "hello world!"
The replace() method replaces a specified value with another value in a
string.
let message = "Please visit Microsoft!";
let newMsg = message.replace("Microsoft", "RedoHub");
console.log(newMsg); // "Please visit RedoHub!"
replace() only replaces the
first match. Use replaceAll() to replace all occurrences.
The trim() method removes whitespace from both sides of a string.
let text = " Hello World! ";
let clean = text.trim();
console.log(clean); // "Hello World!"
A string can be converted into an array with the split() method.
let csv = "Red,Blue,Green";
let colors = csv.split(","); // ["Red", "Blue", "Green"]
You can get specific characters from a string using charAt() or property
access [].
let text = "HELLO";
console.log(text.charAt(0)); // "H"
console.log(text[1]); // "E"
slice() or substring() to get parts of a stringreplace() helps swap text, but usually only for the first matchtrim() is essential for cleaning user input spacessplit() is the way to turn a string into a usable array