How to Find the Index of Specific Character in a String in JavaScript ?
Last Updated :
12 Jan, 2024
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:
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.
Javascript
let str = "Welcome to GeeksforGeeks" ;
let char = "G" ;
let index = str.indexOf(char);
console.log(index);
|
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.
Syntax:
string.search( char )
Example: In this example, we are using the search() method to find the index of G from our given string.
Javascript
let str = "Welcome to GeeksforGeeks" ;
let char = "G" ;
let index = str.search(char);
console.log(index);
|
The match()
method is used to search for and extract substrings from a string based on a specified pattern. It allows you to perform powerful string matching using regular expressions or simple string patterns.
Syntax:
string.match(char)
Example: In this example, we are using the match() method to find the index of G from our given string.
Javascript
let str = "Welcome to GeeksforGeeks" ;
let char = "G" ;
let index = str.match(char);
console.log(index.index);
|
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.
Syntax:
str.lastIndexOf(char);
Example: In this example, we are using the lastIndexOf() method to find the index of G from our given string.
Javascript
let str = "Welcome to GeeksforGeeks" ;
let char = "G" ;
let index = str.lastIndexOf(char);
console.log(index);
|
lodash _.indexOf() method is used to get the index of the first occurrence of the particular element in the array. If fromIndex is not present in the array negative one is given as the output and no error is displayed.
Syntax:
indexOf(array, value, fromIndex);
Example: In this example, we are getting the index at which the given value is present in the given array.
Javascript
const _ = require( "lodash" );
let array = [1, 2, 3, 4]
let index = _.indexOf(array, 3, 0)
console.log( "Index : " , index)
|
Output:
2
Share your thoughts in the comments
Please Login to comment...