How to usea for loop in Javascript
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 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()
Contact Us