JS判断字符串中是否包含某个字段

166 阅读1分钟

2021030114201311880.png

方法一:使用 String.prototype.includes()

includes() 方法用于判断一个字符串是否包含另一个字符串,返回一个布尔值(true 或 false)。

const str = "Hello, world!";
const substring = "world";

if (str.includes(substring)) {
    console.log("The substring exists in the string.");
} else {
    console.log("The substring does not exist in the string.");
}

方法二:使用 String.prototype.indexOf()

indexOf() 方法返回子字符串在字符串中第一次出现的位置,如果未找到则返回 -1。

const str = "Hello, world!";
const substring = "world";

if (str.indexOf(substring) !== -1) {
    console.log("The substring exists in the string.");
} else {
    console.log("The substring does not exist in the string.");
}

方法三:使用正则表达式

可以使用正则表达式来判断子字符串是否存在。

const str = "Hello, world!";
const substring = "world";
const regex = new RegExp(substring);

if (regex.test(str)) {
    console.log("The substring exists in the string.");
} else {
    console.log("The substring does not exist in the string.");
}

方法四:使用 String.prototype.search()

search() 方法用于检索与正则表达式相匹配的子字符串,返回第一个匹配结果的索引,如果未找到则返回 -1。

const str = "Hello, world!";
const substring = "world";

if (str.search(substring) !== -1) {
    console.log("The substring exists in the string.");
} else {
    console.log("The substring does not exist in the string.");
}

方法五:使用 ES6 模板字符串和 includes()

利用模板字符串的特性,可以进行更灵活的匹配。

const str = "Hello, world!";
const substring = `world`;

if (str.includes(`${substring}`)) {
    console.log("The substring exists in the string.");
} else {
    console.log("The substring does not exist in the string.");
}