JavaScript search method looks for a string and returns the location of its match.
The value to search for can be a string or a regular expression. If the occurrence is found, the position of the string is returned, otherwise the value -1 is returned.
The syntax is therefore as follows: string.search (valueToSearch).
Therefore, the method accepts a mandatory parameter, valueToFind, which represents the value to search for in the string.
JavaScript search – examples
In this first example we will search for the occurrence of a string in a simple sentence.
Here is a possible implementation:
var sentence = 'making coding creativo at school';
var sentenceSearch = sentence.search('school');
console.log(sentenceSearch);
In this way, you will get the position of the word school which corresponds to position 27.
If, on the other hand, we look for a word that does not exist in the sentence, we will get the value -1, as in the example below:
var sentence = 'making coding creativo at school';
var sentenceSearch = sentence.search('school');
console.log(sentenceSearch);
JavaScript search – regular expressions
JavaScript search method is case sensitive! So if for example we try to search for School with a capital S, we will get the return value -1, indicating that the string was not found.
To obtain a case insensitive search we must use a regular expression and in particular we will need the modifier i which performs the correspondence without distinction between upper and lower case, as in the example below:
var sentence = 'making coding creativo at school';
var sentenceSearch = sentence.search(/School/i);
console.log(sentenceSearch);
As we can see, we used slashes instead of quotes.
Conclusion
In this lesson we have implemented some very simple examples of using the search method in JavaScript and we have also mentioned regular expressions. We’ll get back to talking about regular expressions further on in our JavaScript tutorial.
Some useful links
Introduction to JavaScript language
Learn JavaScript – basic concepts
JavaScript variables and costants