javascript 检查字符串是否存在于另一个字符串的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7273312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:33:12  来源:igfitidea点击:

what is the best way to check if a string exists in another?

javascript

提问by The Mask

Possible Duplicate:
JavaScript: string contains

可能重复:
JavaScript:字符串包含

I'm looking for an algorithm to check if a string exists in another.

我正在寻找一种算法来检查一个字符串是否存在于另一个字符串中。

For example:

例如:

'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

Thanks in advance.

提前致谢。

采纳答案by Digital Plane

Use indexOf:

使用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

You can also extend String.prototypeto have a containsfunction:

您还可以扩展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

回答by JaredPar

As Digital pointed out the indexOfmethod is the way to check. If you want a more declarative name like containsthen you can add it to the Stringprototype.

正如 Digital 指出的那样,indexOf方法是检查的方法。如果你想要一个更具声明性的名称,contains那么你可以将它添加到String原型中。

String.prototype.contains = function(toCheck) {
  return this.indexOf(toCheck) >= 0;
}

After that your original code sample will work as written

之后,您的原始代码示例将按编写的方式工作

回答by Joe

How about going to obscurity:

去默默无闻怎么样:

!!~'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);

Using Bitwise NOT and to boolean NOTs to convert it to a boolean than convert it back.

使用按位非和布尔非将其转换为布尔值而不是将其转换回来。

回答by clarkb86

I would suppose that using pre-compiled Perl-based regular expression would be pretty efficient.

我认为使用预编译的基于 Perl 的正则表达式会非常有效。

RegEx rx = new Regex('Hello, my name is jonh', RegexOptions.Compiled);
rx.IsMatch('Hello, my name is jonh LOL.'); // true

回答by marcelog

another option could be to match a regular expression by using match(): http://www.w3schools.com/jsref/jsref_match.asp.

另一种选择是使用 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' ]