JavaScript - Index of a Character in String
The indexOf() method can be used to find the first index of specific character in a string. This function returns the index of the given character in a given string.
Using indexOf() - Most Used
The indexOf()
method is a method to find the index of the first occurrence of a specific string within a string.
let s = "abcd";
let c = "c";
let index = s.indexOf(c);
console.log(index);
Output
2
Using String lastIndexOf() Method
The lastIndexOf()
method finds the index of the last occurrence of a specific character in a string. It works similarly to indexOf()
but searches from the end of the string.
let s = "Welcome to GeeksforGeeks";
let c = "G";
let index = s.lastIndexOf(c);
console.log(index);
Output
19
Using search()
- Used for Regular Expressions
The search()
method is a powerful tool used to search for a specific substring within a string. It returns the index of the first occurrence of the specified substring.
let s = "abcd";
let c = "c";
let index = s.search(c);
console.log(index);
Output
2
Using match() - Used for Regular Expressions and More options
The match()
method is used to search a string based on a specified pattern. It allows you to perform powerful string matching having options like global search, case insensitive search and provide detailed information.
let s = "abcd";
let c = "c";
let index = s.match(c);
console.log(index.index);
Output
2
Writing your Own Method
In this approach, we can iterate over each character in the string using a for loop and check if it matches the specific character we are looking for. If a match is found, we return the index of that character. If no match is found, we return -1 to indicate that the character is not present in the string.
function findIndex(str, char) {
for (let i = 0; i < str.length; i++) {
if (str[i] === char) {
return i;
}
}
return -1; // Character not found
}
let str = "Welcome to GeeksforGeeks";
let char = "G";
let index = findIndex(str, char);
console.log(index);
Output
11
Using ES6 findIndex() with Array.from() Method
In this approach, we can utilize ES6 features like Array.from() along with the findIndex() method to find the index of a specific character in a string. This method converts the string into an array of characters, then applies the findIndex() method to search for the desired character.
function findIndex(s, c) {
// Convert string to array of characters
let a = Array.from(s);
// Find index of the character using findIndex method
let index = a.findIndex((x) => x === c);
return index;
}
let s = "abcd";
let c = "c";
let index = findIndex(s, c);
console.log(index);
Output
2