JS commonly used string processing method application summary

  • 2020-03-30 03:04:32
  • OfStack

IndexOf () method, looking for string positions from front to back, case sensitive, counting from 0. Similarly, the lastIndexOf() method runs backwards, and the two methods output the same result for the same retrieval criteria

Such as:
 
<script type="text/javascript"> 

var str="Hello World!" 
document.write(str.indexOf("Hello"))//0
document.write(str.indexOf("World"))//The output of 6
document.write(str.indexOf("world"))//Output minus 1, because I didn't see it

</script> 

2. Length, accessed as "xxx. length" because it is the method of a string object
 
<script type="text/javascript"> 

var str="Hello World!" 
document.write(str.length);//The output of 12

</script> 

3. Substr () method for string interception, one required parameter, one optional parameter, counting from 0
 
<script type="text/javascript"> 

var str="Hello World!" 
document.write(str.substr(3));//Output lo World! , starting from the ordinal number of 3 characters (including the ordinal number of 3 characters), only one parameter will be output to the end
document.write(str.substr(3,7));//Output lo Worl. If the first parameter is negative, it is inverted

</script> 

4. CharAt () method that returns the character at the specified position, counting from 0
 
<script type="text/javascript"> 

var str="Hello World!" 
document.write(str.charAt(1));//The output of e

</script> 

5. The split() method, which splits a string into an array of strings
 
<script type="text/javascript"> 

var str="Hello World!" 
document.write(str.split(" "));//Output the Hello, World!
document.write(str.split(""));//Output H, e, l, l, o, W, o, r, l, d,!
document.write(str.split(" ",1));//Output the Hello
"2:3:4:5".split(":")//Will return ["2", "3", "4", "5"]
"|a|b|c".split("|")//Will return ["", "a", "b", "c"]
var words = sentence.split(/s+/)//Use regular expressions as segmentation parameters

</script> 

Related articles: