Determine whether a string contains a specific character or string

In JavaScript, you can use a few different methods to determine whether a string contains a specific character or string. Here are some of the most common methods:

includes() method: This method checks whether a string contains a specific string. It returns true if included, false otherwise.

let str = "Hello, world!";  
let check = "world";  
console.log(str.includes(check)); // 输出:true

indexOf() method: This method returns the index of the first occurrence of a specific string in another string. If the string has never occurred, it returns -1.

let str = "Hello, world!";  
let check = "world";  
console.log(str.indexOf(check)); // 输出:7

Note that the indexOf() method is case-sensitive. If you want to do a case-insensitive check, you can first convert both strings to lowercase or uppercase.

**search() method: **This method will search for a specific string in a string and return the index of the string. If not found, it returns -1.

let str = "Hello, world!";  
let check = "world";  
console.log(str.search(check)); // 输出:7

The search() method is case-sensitive, but you can perform a case-insensitive search by converting the string to a regular expression and using the i` flag.

Using the RegExp object: You can use regular expressions to check whether a string contains a specific pattern. This requires the use of a RegExp object and the test() method.

let str = "Hello, world!";  
let check = /world/;  
console.log(check.test(str)); // 输出:true

These methods provide different ways to check whether a string contains another string, and you can choose the method that best suits your specific needs.

Guess you like

Origin blog.csdn.net/z2000ky/article/details/134851065