如何搜索字符串以查看它是否包含所有子字符串? [英] How can search a string to see if it contains all substrings?

查看:398
本文介绍了如何搜索字符串以查看它是否包含所有子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将使用coffeescript / javascript / jquery,如果一个字符串包含我所有的子字符串,我需要返回true。



数组的子字符串'my','dog','spot'。我需要返回一个真如果我的字符串是成长我的宠物狗被命名为现场。但我需要返回false,如果字符串是我有一个狗叫现场。



我认为有一个方法来做这个与正则表达式,但是看起来不太明白。

解决方案

  var mystring =我的宠物狗被命名为斑点; 
var words = ['my','dog','spot'];

var res = words.every(function(word){
return mystring.indexOf(word)!== -1;
});






如果要在各种部件,给它一个名称,并提供要搜索的字符串作为第二个参数,这使它成为 this 值。

 函数hasWordInString(word){
return this.indexOf(word)!== -1;
}






  var res = words.every(hasWordInString,mystring); 






.every()是如果返回 false ,它会短路,因此一旦找到不匹配的单词,






强制全字匹配 b

如果你想确保匹配的字符串是一个整数字,以避免dog匹配dogma,例如,你将需要使用RegExp字边界:

 函数hasWordInString(word){
return this.match(new RegExp(\\b+ word +\\ b))!= null;
}
var res = words.every(hasWordInString,mystring);


I will be using coffeescript/javascript/jquery and I need to return true if a string contains all of my substrings.

So, lets say that I have an array of substrings 'my', 'dog', 'spot'. I need to return a true if my string is 'growing up my pet dog was named spot'. But I would need to return false if the string was 'I had a dog named spot'.

I am thinking there is a way to do this with a regular expression, but can't seem to figure it out?

解决方案

var mystring = "growing up my pet dog was named spot";
var words = ['my', 'dog', 'spot'];

var res = words.every(function(word) {
    return mystring.indexOf(word) !== -1;
});


If you want to reuse the function in various parts of your application, give it a name, and provide the string to be searched as the second argument, which makes it the this value.

function hasWordInString(word) {
    return this.indexOf(word) !== -1;
}


var res = words.every(hasWordInString, mystring);


The other nice thing about .every() is that it short-circuits if false is returned, so the search stops once a non-matching word is found, making it a little more efficient.


Force whole word matching

If you want to ensure that the matched string is a whole word to avoid "dog" matching "dogma" for example, you will need to make use of RegExp word boundaries:

function hasWordInString(word) {
    return this.match(new RegExp("\\b"+word+"\\b"))!=null;
}
var res = words.every(hasWordInString,mystring);

这篇关于如何搜索字符串以查看它是否包含所有子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆