How to useES6 findIndex() Method with Array.from() in Javascript
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(str, char) {
// Convert string to array of characters
let charArray = Array.from(str);
// Find index of the character using findIndex method
let index = charArray.findIndex((c) => c === char);
return index;
}
let str = "Welcome to w3wiki";
let char = "G";
let index = findIndex(str, char);
console.log(index); // Output: 11
Output
11
How to Find the Index of Specific Character in a String in JavaScript ?
We will see how to find the index of a specific character in a string using JavaScript. A string is a sequence of characters, such as letters, numbers, or symbols, enclosed in single or double quotes. Here we are going to find the index of a specific character from our given string.
Several approaches can be used to find the index of a specific character in a string using JavaScript, which are listed below:
Table of Content
- Approach 1: Using String indexOf() Method
- Approach 2: Using String search() Method
- Approach 3: Using String match() Method
- Approach 4: Using String lastIndexOf() Method
- Approach 5: Using Lodash _.indexOf() Method
- Approach 6: Using a for loop
- Approach 7: Using ES6 findIndex() Method with Array.from()