Working with string variables is one of the most common tasks in applied programming. This determines the fact that there are built-in functions for finding a given substring in a source string in almost every programming language, and most of them even offer several options for implementing this operation. Below are descriptions of several functions of this kind applied to the client-side JavaScript programming language.
Instructions
Step 1
Use the indexOf function to organize a search for a substring in a string variable when scripting in JavaScript. This function provides for the use of two parameters, one of which is the desired substring and is required. Another parameter can indicate the character index in the string variable, from which to start the search for a substring - this parameter is optional and is equal to zero by default. According to the syntax rules of this language, the original string variable must be written before the function and separated from it by a period. For example: "Original string".indexOf ("string", 2) The function returns the index of the first occurrence of the specified substring it encounters in the original string. In the given example, it will return 9. If no matches are found, then indexOf will return -1. Note that this function is case-sensitive when searching.
Step 2
Use the lastIndexOf function to find occurrences of a substring in the opposite direction, that is, starting at the last character of the original string value. The lastIndexOf syntax practically does not differ from the function described above - it can also be passed two parameters, one of which (the required substring) is required. The second parameter of this function can indicate the position of the beginning of the search and must be counted in the direction from the last character to the first. This function is also case-sensitive when searching and returns -1 if no matches are found. Sample: "Source string".lastIndexOf ("string", 2) This function will return -1, since the search will start from the second position from the end of the source string, which will eliminate the search text completely.
Step 3
Use the search function to find an occurrence of a substring using a regular expression (regexp). This function requires only one parameter - a regular expression. Otherwise, the syntax and return values are the same as for the previous functions. Sample: "Source string".search (/ string / i) This example will also return the value 9. Of course, using a regular expression provides a much more fine tuning of the search, but also requires much more system resources, which should not be forgotten when programming enough resource-intensive scripts.