Hi Friends 👋,
Welcome To Infinitbility! ❤️
To search character in a string in javascript, use the indexOf()
method it will return index o character from string else -1.
Today, I’m going to show you How do I search character in a string in javascript, as mentioned above, I’m going to create a sample string variable with data and use the indexOf()
method to find character from string.
Let’s start today’s tutorial on how do you search character in a string in javascript.
Javascript search character in a string
Here, we will do
- Create sample string variable
- Search character in string using
indexOf()
method
// Create sample string variable
let str = "infinitbility";
// Search character in string using `indexOf()` method
let strIndex1 = str.indexOf("y")
console.log("strIndex1", strIndex1)
let strIndex2 = str.indexOf("x")
console.log("strIndex2", strIndex2)
Output
Output:
strIndex1 12
strIndex2 -1
I hope it helps you, All the best 👍.