Home  >  Article  >  Web Front-end  >  Indexof usage in js

Indexof usage in js

下次还敢
下次还敢Original
2024-05-07 19:18:18471browse

The indexOf() method in JavaScript is used to find a specified substring in a string and return its starting index. If the substring is not found, -1 is returned. The syntax is string.indexOf(substring[, startIndex]), and the parameters include the substring to be found and an optional starting index. This method is case-sensitive, supports forward search, and is suitable for scenarios where different strings are distinguished.

Indexof usage in js

##indexOf() Usage in JavaScript

indexOf() Method is used to find the specified substring in a string and return the index position of its first match. If the substring is not found, -1 is returned.

Syntax:

<code class="javascript">string.indexOf(substring[, startIndex])</code>

Parameters:

  • substring: The substring to be found String.
  • startIndex (optional): The index position at which to start the search (starting from 0).

Usage:

<code class="javascript">let str = "Hello World";

// 查找 "World" 的索引位置
console.log(str.indexOf("World")); // 6

// 从索引 2 开始查找
console.log(str.indexOf("World", 2)); // -1

// 查找不存在的子字符串
console.log(str.indexOf("JavaScript")); // -1</code>

Features:

    It is case sensitive.
  • If startIndex is less than 0, search starts from the beginning of the string.
  • If startIndex is greater than the length of the string, -1 is returned.
  • If the substring is the empty string, 0 is returned.

Example:

<code class="javascript">// 查找字符串中第一个 "e" 的索引位置
let str = "Elephant";
let index = str.indexOf("e");

// 如果找到子字符串,则打印其索引
if (index !== -1) {
  console.log(`找到 "e" 的索引位置:${index}`);
}</code>

Note:

indexOf() method for Unicode String support is limited. For more complex string searches, it is recommended to use the search() method or regular expressions.

The above is the detailed content of Indexof usage in js. 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