如何在一个字符串中搜索第二个字符串中包含的所有单词? [英] How to search one string for all of the words contained in a second string?

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

问题描述

我需要检查 string A 是否匹配,具体取决于它是否包含另一个 string B 中的所有单词-顺序是否相同.

I need to check a string A for a match based on whether it contains all of the words in another string B - in whatever order.

因此,假设 string A 是这样的:

So, let's say string A is this:

one two three four five

string B 是其中之一:

And string B is one of these:

one two three // match!
one three two // match! (order doesn't matter)
one two six // NOT A MATCH! ('six' is not found in string A)
one two three four // match!
one two three four five // match!
one two three four five seven // NOT A MATCH! ('seven' is not found in string A)

仅当在 string B 中找到每个单词时,才能找到 string A string B 之间的匹配项strong> string A (无论两个字符串中单词的顺序如何,并且无论 string A 是否包含在 string B 中都找不到的其他单词)?

How would I find a match between string A and string B only if every word in string B is found in string A (regardless of the order of the words in either string and regardless of whether string A contains additional words that are not found in string B)?

我不知道jQuery是否具有任何对此有帮助的特殊功能,或者我是否需要严格使用纯JavaScript?

I don't know if jQuery has any special features that would help with this or whether I need to do it strictly with pure JavaScript?

推荐答案

//如果客户端具有数组方法 every ,则此方法非常有效-

// If the client has the array method every, this method is efficient-

function commonwords(string, wordlist){
    string= string.toLowerCase().split(/\s+/);
    wordlist= wordlist.toLowerCase().split(/\s+/);
    return wordlist.every(function(itm){
        return string.indexOf(itm)!= -1;
    });
}

常用词(一二三四有五",一二有九");

//如果您希望任何客户端在没有特殊功能的情况下进行处理, 您可以解释"高级数组方法-

// If you want any client to handle it without a special function, you can 'explain' the advanced array methods-

Array.prototype.every= Array.prototype.every || function(fun, scope){
    var L= this.length, i= 0;
    if(typeof fun== 'function'){
        while(i<L){
            if(i in this && !fun.call(scope, this[i], i, this)) return false;
            ++i;
        }
        return true;
    }
    return null;
}
Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
    i= i || 0;
    var L= this.length;
    while(i< L){
        if(this[i]=== what) return i;
        ++i;
    }
    return -1;
}

这篇关于如何在一个字符串中搜索第二个字符串中包含的所有单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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