Sometimes we need to check the existence of a character or sub-string into a string or find the position of a character or sub-string into a string.
check a substring into a string
Javascript provides us a very simple method :
indexOf() :
1 | string.indexOf(searchvalue,start) |
searchvalue Required. The string to search for
start Optional. Default 0. At which position to start the search
Return type : number
The indexOf() method returns the position of the first occurrence of a specified value in a string.
This method returns -1 if the value to search for never occurs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Example: Search a string for "best" <script> var str = "Hello world, this is best in the world."; var pos = str.indexOf("best"); if(pos > -1) alert('Found'); else alert('Not found'); </script> The result of pos will be: 21 |
Note:
1. The indexOf() method is case sensitive.
2. It returns position starting from 0
3. It is supported in all major browsers.
See : lastIndexOf()
More Examples:
1 2 3 4 5 6 7 8 9 10 11 | Examples: Find the first occurrence of the letter "o" in a string: <script> var str = "Hello world, this is best in the world."; var pos = str.indexOf("o"); </script> The result of pos will be: 4 |
1 2 3 4 5 6 7 8 9 10 11 | Example: Find the first occurrence of the letter "o" in a string, starting the search at position 5:: <script> var str = "Hello world, this is best in the world."; var pos = str.indexOf("o",5); </script> The result of pos will be: 7 |
Like this, we can check a substring into a string and find the position of substring occurrence in the string.