JavaScript indexOf

 JavaScript indexOf can be used to retrieve the starting position of a character or word in a string. The first character of the string is sorted from zero. Generally speaking, indexof can be used for string comparison, assuming there is a word The string is "Good morning.", we can use indexof to query the first position of the character m or morning in the entire string. Through the JavaScript indexof function, we can know whether it is m or morning. The positions are in the fifth position in the string. In other words, using indexof can also query whether a character or word exists in a string.


JavaScript indexOf basic syntax

String.indexof (character or word to be searched, search start position)


String is the string to be retrieved, indexof will automatically compare whether there is a "character or word to be retrieved" in String, and if so, return the starting position in the string, if not found, return- 1 For this result, the second parameter "search start position" in parentheses is an optional item, used to tell JavaScript indexof from which position in the string to start searching, and the returned position is still the first position from the front Start counting from zero characters.

JavaScript indexOf usage example
<script language='javascript'>
 Str = "ABCDEFABCDEF";
 document.write(Str.indexOf("d")); // output -1
 document.write(Str.indexOf("D")); // output 3
 document.write(Str.indexOf("D",5)); // output 9
</script>

The example first prepares a string String, and then uses document.write to output three different results. The first output result is -1, which means that indexof did not find the letter "d" in the string. This is because indexof will distinguish between uppercase and lowercase. The second output will find the letter "D" in the third position in the string (counting from 0), and the third output will be 9 because we have enabled the second parameter , Tells JavaScript to search from the 5th character, so the first letter "D" is skipped, and the second letter "D" is found directly, and its position is counted from the 0th character At the ninth position, these examples should have a good idea of ​​the function of JavaScript indexof!

Post a Comment

0 Comments