当前位置: 首页> 财经> 股票 > js中怎么判断字符串是否包含

js中怎么判断字符串是否包含

时间:2025/9/2 16:36:07来源:https://blog.csdn.net/fzxyxf1314/article/details/140887539 浏览次数:0次

在JavaScript中,我们可以使用以下方法来判断一个字符串是否包含另一个字符串:

方法一:使用indexOf()方法

const str = "Hello World";
const substring = "World";
if (str.indexOf(substring) !== -1) {console.log("字符串包含指定的子字符串");
} else {console.log("字符串不包含指定的子字符串");
}

方法二:使用includes()方法

const str = "Hello World";
const substring = "World";
if (str.includes(substring)) {console.log("字符串包含指定的子字符串");
} else {console.log("字符串不包含指定的子字符串");
}

方法三:使用正则表达式的test()方法

const str = "Hello World";
const regex = /World/;
if (regex.test(str)) {console.log("字符串包含指定的子字符串");
} else {console.log("字符串不包含指定的子字符串");
}

这些方法都可以用来判断一个字符串是否包含另一个字符串,根据具体的使用场景和需求,可以选择适合的方法来完成判断。

每天分享一点知识!

关键字:js中怎么判断字符串是否包含

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: