检查字符串是否存在于另一个字符串中的最佳方法是什么
what is the best way to check if a string exists in another?
可能重复:
JavaScript:字符串包含
我正在寻找一种算法来检查另一个字符串中是否存在字符串。
例如:
'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
正如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);
使用Bitwise NOT和to boolean NOTs将其转换为布尔值,而不是将其转换回布尔值。
另一个选项可以是使用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' ]
我认为使用预编译的基于Perl的正则表达式会非常有效。
RegEx rx = new Regex('Hello, my name is jonh', RegexOptions.Compiled);
rx.IsMatch('Hello, my name is jonh LOL.'); // true
相关文章:
- 将大数组(字符串和类型数组的混合物)存储到blob或文件中/从blob或文件检索大数组的最佳方式
- 使用 MVC 删除 JavaScript 中硬编码字符串 Asp.Net 最佳方法
- 检测在angular中传递给$compile的字符串的最佳方法是可编译的
- 将64位整数转换为json编码对象中的字符串的最佳实践
- 从正则表达式文本中获取正则表达式字符串表示的最佳方式
- 通过 jQuery 验证日期字符串格式的最佳方法
- 检查另一个字符串 JavaScript 中一个字符串是否有任何字符的最佳方法
- 用字符串填充数组的最佳方法
- 量角器 - 在 e2e 测试中检查字符串的最佳方法不为空
- Javascript:生成唯一数字字符串的最佳方法是什么
- 查找警告源的最佳方法:传递给getElementById()的空字符串
- Javascript从字符串中提取特定文本的最佳方法
- 字符串中包含的大型基数 10 的数字的最佳压缩
- 从字符串中拆分字母和数字部分的最佳方法是什么
- 在 JavaScript 字符串数组中获取相邻字符的最佳方法是什么?
- 在 js 中验证字符串的最佳方法
- 创建字符串中找到的所有图像的数组的最佳方法是什么
- 获取构造函数函数的最佳方式是在JavaScript中使用带名称空间的字符串表示
- 在Javascript中将字符串文本提取为常量是一种最佳实践吗
- 使用javaScript查找字符串中每次出现重复单词的起始索引的最佳方法