是的,使用
.match而不是
.search。
.match调用的结果将返回匹配自身的实际字符串,但仍可以将其用作布尔值。
var string = "Stackoverflow is the BEST";var result = string.match(/best/i);// result == 'BEST';if (result){ alert('Matched');}在Javascript中使用这样的正则表达式可能是最整齐,最明显的方法,但是请记住,它 是
一个正则表达式,因此可以包含regex元字符。如果您想从其他地方获取字符串(例如,用户输入),或者想要避免不得不转义许多元字符,那么最好使用
indexOf这样的方法:
matchString = 'best';// If the match string is coming from user input you could do// matchString = userInput.toLowerCase() here.if (string.toLowerCase().indexOf(matchString) != -1){ alert('Matched');}


