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);
var array1 = [ '张三', '李四', '王二', '陈五' ]; var index3 = array1.indexOf('李四'); console.log(index3);
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!