📜  string.find javascript (1)

📅  最后修改于: 2023-12-03 15:20:21.611000             🧑  作者: Mango

String.find() in JavaScript

Introduction

The String.find() method in JavaScript is used to search for a particular substring within a string and returns the index of the first occurrence of the substring.

Syntax
str.find(searchValue[, fromIndex])
Parameters
  • searchValue: The substring to search for within the string.
  • fromIndex (optional): The index to start searching from. If not specified, it defaults to 0.
Return value
  • Returns the index of the first occurrence of the substring within the string. Returns -1 if the substring is not found.
Examples
let str = "Hello World!";

console.log(str.find("world")); // returns -1
console.log(str.find("World")); // returns 6
console.log(str.find("o"));     // returns 4
console.log(str.find("o", 5));  // returns 7
Notes
  • The String.find() method is case-sensitive.
  • The fromIndex parameter accepts negative values, which count backwards from the end of the string.
Conclusion

The String.find() method in JavaScript is a useful tool for searching strings for substrings. By understanding its syntax, parameters, and return values, programmers can efficiently find substrings within strings for their applications.