检查另一个字符串是否存在的最佳方法是什么?
我正在寻找一种算法,以检查是否在另一个存在的字符串。
例如:
'Hello, my name is jonh LOL.'.contains('Hello, my name is jonh'); //true
'LOL. Hello, my name is jonh'.contains('Hello, my name is jonh'); //true
预先感谢。
使用indexOf
:
'Hello, my name is jonh LOL.'.indexOf('Hello, my name is jonh') > -1; //true
'LOL. Hello, my name is jonh'.indexOf('Hello, my name is jonh') > -1; //true
您还可以扩展String.prototype
有contains
功能:
String.prototype.contains = function(substr) {
return this.indexOf(substr) > -1;
}
'Hello, my name is jonh LOL.'.contains('Hello, my name is jonh'); //true
'LOL. Hello, my name is jonh'.contains('Hello, my name is jonh'); //true
对此答案更进一步,您可以创建'function contains(haystack,needle){返回haystack.indexOf(针)> -1; }'或者甚至在String原型上创建一个 –
@Jonathan我添加了一个'String.prototype'函数。 –
感谢您的原型功能灵活性课! – blackhawk
我会假设使用预编译的基于Perl的正则表达式将是非常有效的。
RegEx rx = new Regex('Hello, my name is jonh', RegexOptions.Compiled);
rx.IsMatch('Hello, my name is jonh LOL.'); // true
我正在使用JavaScript,但感谢:P –
更好: 'var regex = /你好,我的名字是jonh /; regex.test(“你好,我的名字是jonh LOL。”); // true' – clarkb86
另一个选项可能是通过使用match()匹配正则表达式:http://www.w3schools.com/jsref/jsref_match.asp。
> var foo = "foo";
> console.log(foo.match(/bar/));
null
> console.log(foo.match(/foo/));
[ 'foo', index: 0, input: 'foo' ]
As Digital指出indexOf
方法是检查的方法。如果您想要一个更具说明性的名称,例如contains
,则可以将其添加到String
原型。
String.prototype.contains = function(toCheck) {
return this.indexOf(toCheck) >= 0;
}
之后,你原来的代码示例将作为书面
如何去默默无闻:
!!~'Hello, my name is jonh LOL.'.indexOf('Hello, my name is jonh'); //true
if(~'LOL. Hello, my name is jonh'.indexOf('Hello, my name is jonh'))
alert(true);
使用逐不要和布尔组合这些将其转换为一个布尔比将其转换背部。
这里是检查字符串是否在字符串中的最常用方法的基准:http://jsben.ch/#/o6KmH – EscapeNetscape