๐ฆString Methods
In JavaScript, strings are objects that have built-in methods that can be used to manipulate and analyze the string. Here are some of the most commonly used string methods:
length: returns the number of characters in a string.
let myString = "Hello World";
console.log(myString.length); // Output: 11charAt(index): returns the character at a specified index in a string. The first character has an index of 0.
let myString = "Hello World";
console.log(myString.charAt(0)); // Output: "H"
console.log(myString.charAt(5)); // Output: " "indexOf(searchValue, [start]): returns the index of the first occurrence of a specified value in a string. If the value is not found, it returns -1. The optional start parameter specifies the position to start the search from.
let myString = "Hello World";
console.log(myString.indexOf("o")); // Output: 4
console.log(myString.indexOf("o", 5)); // Output: 7lastIndexOf(searchValue, [start]): returns the index of the last occurrence of a specified value in a string. If the value is not found, it returns -1. The optional start parameter specifies the position to start the search from, searching backwards.
let myString = "Hello World";
console.log(myString.lastIndexOf("o")); // Output: 7
console.log(myString.lastIndexOf("o", 6)); // Output: 4slice(start, [end]): returns a portion of a string as a new string. The start parameter specifies the index of the first character to include, and the optional end parameter specifies the index of the last character to include.
let myString = "Hello World";
console.log(myString.slice(0, 5)); // Output: "Hello"
console.log(myString.slice(6)); // Output: "World"substring(start, [end]): returns a portion of a string as a new string. It's similar to slice but it can't accept negative values as input.
let myString = "Hello World";
console.log(myString.substring(0, 5)); // Output: "Hello"
console.log(myString.substring(6)); // Output: "World"substr(start, [length]): returns a portion of a string as a new string. The start parameter specifies the index of the first character to include, and the optional length parameter specifies the number of characters to include.
let myString = "Hello World";
console.log(myString.substr(0, 5)); // Output: "Hello"
console.log(myString.substr(6, 4)); // Output: "Worl"replace(searchValue, replaceValue): replaces the first occurrence of a specified value with another value.
let myString = "Hello World";
console.log(myString.replace("World", "Friend")); // Output: "Hello Friend"Last updated