我需要你的帮助,
使用javascript,如何判断匹配是否在字符串中?
var x = "APPLE-PEAR/BANANA and ORANGE & LEMON"
所以我需要一个允许我根据值x检查值y的函数。
要搜索的值:
y = "PEAR"
if (y matches the string in x) then return true
答案 0 :(得分:0)
var x = "APPLE-PEAR/BANANA and ORANGE & LEMON"
y = "PEAR"
// Checks if string x having string y
if(x.includes(y)) { console.log("MATCH FOUND"); return true; }
// Returns index of string y in x , -1 if not present
if(x.indexOf(y) > -1) { console.log("MATCH FOUND"); return true; }
有很多方法可以做到这一点。请阅读Javascript String对象的文档
答案 1 :(得分:0)
indexOf()
方法返回第一次出现的指定值的调用String对象中的索引,从fromIndex开始搜索。如果找不到值,则返回-1
。
var x = "APPLE-PEAR/BANANA and ORANGE & LEMON",
y = "PEAR";
console.log(x.indexOf(y) !== -1); //If true, exist