Home > Article > Web Front-end > How to use indexOf in JavaScript
If you want to retrieve whether a string contains a certain character? In this case, you can use the indexOf function, which returns the first occurrence of a specified string value in the string.
#The indexOf function searches a string for a specified character and, if present, returns the position.
How to use indexOf function
The basic procedure is as follows
String.indexOf( 检索的字符[, 检索开始的位置])
Use indexOf to search strings
The code is as follows
<!DOCTYPE html> <html lang = "ja"> <head> <meta charset = "utf-8"> <title>How to use indexOf in How to use indexOf in JavaScript</title> </head> <body> <script> var str1 = '英语,中文,法语,阿拉伯语,中文'; var index1 = str1.indexOf('中文'); console.log(index1); var index2 = str1.indexOf('中文', 7); console.log(index2); var array1 = [ '张三', '李四', '王二', '陈五' ]; var index3 = array1.indexOf('李四'); console.log(index3); </script> </body> </html>
The running results are as follows
var str1 = '英语,中文,法语,阿拉伯语,中文'; var index1 = str1.indexOf('中文'); console.log(index1); var index2 = str1.indexOf('中文', 7); console.log(index2);The above is the code to retrieve the string, and the character position is counted as "0" at the beginning. If no characters are found, "-1" is returned. We set a variable of "str 1", use indexOf to search for the character "Chinese", and put the result in a variable named "index 1". As a result, the number "3" is output. The second one is to specify the starting position as "7". In this case, we will search from the seventh letter. As a result, the number "14" is output.
var array1 = [ '张三', '李四', '王二', '陈五' ]; var index3 = array1.indexOf('李四'); console.log(index3);The above is the code to retrieve the array. We set the array "array1" and use indexOf to search for "John Doe". Although the corresponding element is the second one, the output is "1" because the array starts at "0".
The above is the detailed content of How to use indexOf in JavaScript. For more information, please follow other related articles on the PHP Chinese website!