We often need to look for some characters in the string or some content in html. Next I will introduce how to use the js indexOf method, according to the syntax of the indexOf method, stringObject. indexOf (the string to be searched, the position where the search starts) will return the position where a specified string value first appears in the string. This is simple. The example is as follows.
Html code
The Code is as follows: |
Copy code |
<Dl class = "forum_0_1_3"> <Dt> something </dt> <Dd> do something </dd> </Dl> <Dl class = "forum_0_00004_7"> <Dt> something </dt> <Dd> do something </dd> </Dl> <Dl class = "forum_0_4"> <Dt> something </dt> <Dd> do something </dd> </Dl> |
JavaSctipt (jQuery ):
The Code is as follows: |
Copy code |
$ (Function (){ $ ('Dl '). each (function (){ Var classStr = $ (this). attr ('class '); If (classStr. indexOf ("1")> 0 ){ Console. log ("this class contains 1 "); } If (classStr. indexOf ("4")> 0 ){ Console. log ("this class contains 4 "); } If (classStr. indexOf ("7")> 0 ){ Console. log ("this class contains 7 "); } }); }) |
The indexOf () method is case sensitive. Therefore, you must note the case sensitivity of the string to be retrieved.
Instance:
The Code is as follows: |
Copy code |
<Script type = "text/javascript"> Var str = "ant school _ http://www.bKjia. c0m" Document. write (str. indexOf ("ant") + "<br/> ") Document. write (str. indexOf ("cn") + "<br/> ") Document. write (str. indexOf (". com ")) </Script> |
Output result:
0
-1
27