问题描述
我遇到了将子字符串与String匹配的问题。我的子串和字符串类似于
I am facing a problem in matching a substring with a String. My substring and string are something like
var str="My name is foo.I have bag(s)"
var substr="I have bag(s)"
现在当我使用 str时。匹配(substr)它返回null可能是因为match()函数将输入作为正则表达式而在我的情况下它与'('。'我尝试使用'\'在圆括号之前但它没有工作。 indexOf()函数正在运行但我不允许使用它。我也使用了test()和exec()但没有成功
now when I use str.match(substr) it returns null probably because match() function takes input as a regex and in my case it gets confused with the '('. I tried using '\'before round brackets but it didn't worked. indexOf() function is working but I am not allowed to use that. I also used test() and exec() but without any success
推荐答案
在现代引擎中,您只需使用:
In modern engines you can just use String.prototype.includes:
str.includes( substr )
如果你想要一些适用于旧浏览器的东西并避免,您可以通过手动循环实现 includes
通过字符串:
If you want something that works in older browsers and avoids String.prototype.indexOf, you could implement includes
, by manually loop through the string:
String.prototype.includes = function ( substr, start ) {
var i = typeof start === 'number' ? start : 0;
// Condition exists early if there are not enough characters
// left in substr for j to ever reach substr.length
for ( var j = 0; i + substr.length < this.length + j + 1; ++i ) {
j = substr[j] === this[i] ? j + 1 : 0;
if ( j === substr.length )
return true;
}
return false;
};
如果您坚持使用正则表达式测试,可以使用,正确地使用正则表达式中使用的substr;在这种情况下,它在(
和)
之前添加反斜杠:
If you are insistent on using a regex test you can use the escape function from this answer, to properly espace the substr to be used in a regex; in this case it adds a backslash before the (
and )
:
new RegExp( substr.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') ).test( str )
这篇关于将子字符串与字符串匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!