Home  >  Article  >  Web Front-end  >  How to use indexOf in JavaScript

How to use indexOf in JavaScript

不言
不言Original
2018-12-24 13:37:4010119browse

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.

How to use indexOf in How to use indexOf in JavaScript

#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 = &#39;英语,中文,法语,阿拉伯语,中文&#39;;
    var index1 = str1.indexOf(&#39;中文&#39;);
    console.log(index1);
    var index2 = str1.indexOf(&#39;中文&#39;, 7);
    console.log(index2);
    var array1 = [ &#39;张三&#39;, &#39;李四&#39;, &#39;王二&#39;, &#39;陈五&#39; ];
    var index3 = array1.indexOf(&#39;李四&#39;);
    console.log(index3);
    </script>
  </body>
</html>

The running results are as follows

How to use indexOf in How to use indexOf in JavaScript

##We analyze the above code carefully

var str1 = &#39;英语,中文,法语,阿拉伯语,中文&#39;;
var index1 = str1.indexOf(&#39;中文&#39;);
console.log(index1);
var index2 = str1.indexOf(&#39;中文&#39;, 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 = [ &#39;张三&#39;, &#39;李四&#39;, &#39;王二&#39;, &#39;陈五&#39; ];
var index3 = array1.indexOf(&#39;李四&#39;);
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn