Indexof in Javascript
The indexOf()
method returns the index
of the first occurrence of the specified string or character within the given string. If the specified string or character is not found, it returns -1
.
const str = "Hello, Skillupwards!";
console.log(str.indexOf("o")); // Output: 4
console.log(str.indexOf("x")); // Output: -1
There are many other methods that can be used to search for a string or character within a string.
Let's explore them one by one.
The lastIndexOf()
method
The lastIndexOf()
method is similar to the indexOf()
method, but it returns the index of the last occurrence of the specified string or character within the given string.
const str = "Hello, Skillupwards!";
console.log(str.lastIndexOf("l")); // Output: 11
console.log(str.lastIndexOf("x")); // Output: -1
The search()
method
The search()
method searches a string for a specified value and returns the position of the match. It supports regular expressions.
const str = "Hello, Skillupwards!";
console.log(str.search("o")); // Output: 4
console.log(str.search(/W/)); // Output: -1
The match()
method
The match()
method searches a string for a specified value and returns an array of the matches. It also supports regular expressions.
const str = "The quick brown fox jumps over the lazy dog";
console.log(str.match(/o/g)); // Output: ["o", "o", "o"]
console.log(str.match(/z/)); // Output: null
The includes()
method
The includes()
method determines whether a string contains the specified value and returns a boolean value.
const str = "Hello, Skillupwards!";
console.log(str.includes("Skillupwards")); // Output: true
console.log(str.includes("JavaScript")); // Output: false
The startsWith()
method
The startsWith()
method determines whether a string starts with the specified value and returns a boolean value.
const str = "Hello, Skillupwards!";
console.log(str.startsWith("Hello")); // Output: true
console.log(str.startsWith("Skillupwards")); // Output: false
The endsWith()
method
The endsWith()
method determines whether a string ends with the specified value and returns a boolean value.
const str = "Hello, Skillupwards!";
console.log(str.endsWith("Skillupwards!")); // Output: true
console.log(str.endsWith("Hello")); // Output: false
The charAt()
method
The charAt()
method returns the character at the specified index within the string. If the index is out of range, it returns an empty string.
const str = "Hello, Skillupwards!";
console.log(str.charAt(4)); // Output: "o"
console.log(str.charAt(20)); // Output: ""