How to useString indexOf() Method in Javascript
The indexOf()
method is a method to find the index of the first occurrence of a specific character within a string. It takes the character as an argument and returns the index of its first appearance.
Syntax:
str.indexOf(searchValue , index)
Example: In this example, we are using the indexOf() method to find the index of G from our given string.
let str = "Welcome to w3wiki";
let char = "G";
let index = str.indexOf(char);
console.log(index);
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