In Javascript there are several built in functions that allow us to search for text within a string. In this tutorial we will be covering the following three functions:
-
indexOf()
-
lastIndexOf()
-
search()
Searching for text within a string using indexOf()
The indexOf() function takes a single argument which is the text we are looking for within the string, if a match is found, it will return the start index for the location of the match within the string. The indexOf() function will only return the location of the first occurrence of the text we are searching for, any further matches within the string will be ignored. If there is no match within the string, then indexOf() will return -1.
string.indexOf(searchText);
Say we wanted to search the string "May the force be with you" for an occurrence of the word "force", then we could make use of the following code:
var string1 = "May the force be with you";
var location = string1.indexOf("force");
Here the indexOf() function will return the index 8, as it will find the text "force" within string1 at position 8.
If we wanted to search the string "Hello world, Hello world" for the occurrence of the word "world", then we could make use of the following code:
var string1 = "Hello world, Hello world";
var location = string1.indexOf("world");
Here the indexOf() function will only return the index of the first occurrence of "world" which is 6. Once it finds a single occurrence of the given text, it will stop looking and only return the location of the first occurrence.
Searching for the last occurrence of text using lastIndexOf()
The lastIndexOf() function works similarly to indexOf() in that it searches for a given text within a string and returns the starting positional index, except this function will only return the position of the last occurrence of the text.
string.lastIndexOf(searchText);
So if we searched the string "Hello world, Hello world" for the word "world" using the lastIndexOf() function then we could use the following code:
var string1 = "Hello world, Hello world";
var location = string1.lastIndexOf("world");
This time it would return the starting index of the last occurrence of the word "world" which would be 19.
Searching for text within a string using search()
The search() function is almost identical to the indexOf() function in that it searches a string for the given text value and returns the starting index for the first occurrence of it, except this function can also take a regular expression as an argument, allowing for more complex searches.
string.search(searchText);
So if we wanted to search the string "Hello world" for the first occurrence of a white space character we could use the following code:
var string1 = "Hello world";
var location = string1.search(/\s/);
This would return the starting index of the first and only white space in the string which would be 5.