person github
In JavaScript, there are various ways to check if a string contains another string:
1. String.prototype.includes()
This method returns a Boolean value indicating whether one string contains another string.
const str = "Hello, world!";
const result = str.includes("world"); // 返回 true
2. String.prototype.indexOf()
This method returns an integer representing the index position of the first occurrence of the substring in the string, or -1 if not found.
const str = "Hello, world!";
const result = str.indexOf("world"); // 返回 7
3. String.prototype.search()
This method performs a regular expression search and returns an integer indicating the position of the match in the string, or -1 if not found.
const str = "Hello, world!";
const result = str.search("world"); // 返回 7
4. Regular expressions
You can also use regular expressions test()
to check if a string contains another string.
const str = "Hello, world!";
const regex = /world/;
const result = regex.test(str); // 返回 true
Each of these methods has its uses and limitations, and you can choose the method that works best for you based on your specific needs.