js字符串包含判断是指对字符串进行判断,判断字符串是否包含另一个字符串。js中有几种实现方法,可以根据实际情况选择。
1.使用indexOf方法:indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。
var str="Hello world";
if (str.indexOf("world") != -1)
{
document.write("字符串中包含world");
}
else
{
document.write("字符串中不包含world");
}
2.使用includes方法:includes() 方法用来判断一个字符串是否包含在另一个字符串中,根据判断结果返回 true 或 false。
var str="Hello world";
if (str.includes("world"))
{
document.write("字符串中包含world");
}
else
{
document.write("字符串中不包含world");
}
3.使用search方法:search() 方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串,并返回子串的起始位置。
var str="Hello world";
if (str.search("world") != -1)
{
document.write("字符串中包含world");
}
else
{
document.write("字符串中不包含world");
}
4.使用match方法:match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。
var str="Hello world";
if (str.match("world"))
{
document.write("字符串中包含world");
}
else
{
document.write("字符串中不包含world");
}
以上是,可以根据实际情况选择。