There are many methods to search for characters in js. One is to search for a specific string and return a string, and the other is to find the position of the string. I will share with you their implementation methods.
Searches for a specific character in a string. If yes, this character is returned.
Example 1 match () function
The Code is as follows: |
Copy code |
<Script type = "text/javascript"> Var str = "heyanping" Document. write (str. match ("ing") + "<br/>") // The result is ing, because the "heyanping" string contains ing Document. write (str. match ("img") + "<br/>") // The result is null because the "heyanping" string does not contain img </Script> |
Example 2
IndexOf can return the position of a specified string. This function returns an integer. Note: The characters in javascript are counted from 0. Below is a simple example:
The Code is as follows: |
Copy code |
<Script type = "text/javascript">
Var my_str = "Welcome to www. bKjia. c0m" Document. write (my_str.indexOf ("share ")) </Script> |
The Return Value of the code above is 15.
LastIndexOf function:
The lastIndexOf function is also used to return the position of a string. Unlike indexOf, it searches forward from the end of a string and returns the position at which the string appears, through this function, we can find the final position of the specified string.
The following is an example:
The Code is as follows: |
Copy code |
Var my_str = "Welcome to www. bKjia. c0m" Document. write (my_str.lastIndexOf ("o ")) |
The output result of the above Code is 24, that is, the position where the last o appears.
Count the number of occurrences of characters in a string
Let's take a look at the Code provided by cloudchen that uses regular expressions:
The Code is as follows: |
Copy code |
<Script language = "JavaScript"> Var str = "cloudchen"; var find = "c "; Var reg = new RegExp (find, "g ") Var c = str. match (reg ); Alert (c? C. length: 0) </SCRIPT> Var reg = new RegExp (find, "g ") |
A regular expression can be written as follows:
Var reg =/c/g; c indicates the character to be matched, where g indicates global search. Match returns the matched characters (strings ). In this way, the number of occurrences of the specified character in the string is obtained. This is a very formal practice.