Find Character in String Javascript
Learn how to find character in string javascript with three easy steps.
1. Create a JavaScript String
We can create a String in JS using the “let” keyword. To create a String, first, put “let” then give “string name” then put “=” equal to the operator, and then assign value to the string. You can name the string however you like, and in this guide, I have named the “str” as an example. Remember that, You should always enclose the value of a string in double quotes as in the below example.
Ex:
let str = "Hello World";
2. Finding Character in String
To find a particular character in the JS string, we need to use the “indexOf()” function.
- Give the string name in which we want to find the character.
- Then “indexOf()” function should be selected using the dot operator (.)
- The character you want to find must also be enclosed in double quotes in the indexOf() function.
3. Output
Your output will execute in the array index. The array index starts from the number 0. If you get output 0, your searched character is placed in the first position. If you get output 1, your searched character is placed in the second position. So, If you subtract 1 from the output you get, you will get the character position you searched for.
Ex:
document.write(str.indexOf("H"))
The final code should look like this:
let str="Hello World";
document.write(str.indexOf("H"))
Output:
0