首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何搜索字符串以查找多维数组中的关键字?

如何搜索字符串以查找多维数组中的关键字?
EN

Stack Overflow用户
提问于 2011-04-02 14:14:30
回答 4查看 1.1K关注 0票数 2

所以我有一些数据如下:

代码语言:javascript
运行
复制
stringToSearch = 'this string needs to be searched';

labels = ['keys 1-3','keys 4-6','keys 7-9'];

keywords =
    ['key1', 'key2', 'key3'],
    ['key4', 'key5', 'key6'],
    ['key7', 'key8', 'key9']
];

编辑:基本上,我试图实现的是,搜索字符串中的任何一个键。然后查找与键所在的组对应的所有标签。

编辑:目标是传递字符串并取回标签。

string='this包含key5和key9 9‘;

因此,它返回标签‘键4-6’和‘键7-9’。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-04-02 16:09:13

以下是基于您最近编辑的另一种解决方案:

代码语言:javascript
运行
复制
stringToSearch = 'this string needs to be searched';

labelsToApply = {
    myFirstLabel: ['key1', 'key2', 'key3'],
    anotherLabel: ['key4', 'key5', 'key6'],
    lastLabel:    ['key7', 'key8', 'key9', 'key10', 'key11'],
}

function getLabels(str, labels) {
    var appliedLabels = [];
    $.each(labels, function(labelName, keywords) {
        $.each(keywords, function() {
             if(str.search(this) >= 0) {
                 appliedLabels.push(labelName);
                 return false;
             }
        });  
    });
    return appliedLabels;
}

alert(getLabels(stringToSearch, labelsToApply));
票数 1
EN

Stack Overflow用户

发布于 2011-04-02 14:37:07

试试这个:

代码语言:javascript
运行
复制
stringsToSearch = ['this string needs to be searched', '...']

keywords = {
    firstGroup: {
        key1: [],
        key2: [],
        key3: []
    },
    secondGroup: {
        key4: [],
        key5: [],
        key6: []
    },
    thirdGroup: {
        key7: [],
        key8: [],
        key9: []
    }
}

$.each(keywords, function(groupName, keyGroup) {
    $.each(keyGroup, function(key, foundStrings) {
        $.each(stringsToSearch, function() {
            if(this.search(key) >= 0)
                foundStrings.push(this);
        });
    });
});
票数 2
EN

Stack Overflow用户

发布于 2011-04-02 14:45:41

在普通的旧Javascript中,我会使用这样的东西:

代码语言:javascript
运行
复制
var stringToSearch = 'this string needs to be key2 searched key4';

var Keywords = function(keywords, label) {
    this.keywords = keywords;
    this.label = label;
}

var keywords1 = new Keywords(['key1', 'key2', 'key3'], 'keys 1-3');
var keywords2 = new Keywords(['key4', 'key5', 'key6'], 'keys 4-6');

var keywordsArray = [ keywords1, keywords2 ];

for (var i=0; i <keywordsArray.length; i++) {
    var keywordsEntry = keywordsArray[i];
    for(var j=0; j <keywordsEntry.keywords.length; j++) {
        // here you got the index of the occuring keyword
        if(stringToSearch.indexOf(keywordsEntry.keywords[j]) > 0) {
            // now do sth. with the label
            alert(keywordsEntry.label);
        }
    }
}

(绝对不是很好的编码,但这是为了给您一个开始。)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5523663

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档