简体   繁体   English

如何检查给定字符串中数组中的单词是否存在

[英]How to check if word in array exists in a given string

I'm trying to create suggested tags, first i take input string while the user is typing, then check for words from a long list of words in an array, if word exists in the first array, check other arrays categories that this word falls into, then append some tag in an input. 我正在尝试创建建议的标签,首先我在用户输入时获取输入字符串,然后检查数组中单词的长列表中的单词,如果单词存在于第一个数组中,请检查该单词属于其他数组类别放入,然后在输入中附加一些标签。

First Problem : So far i can only check if a string contains a word, i don't know how to search an array so i can find words in a given string that match words in an array. 第一个问题 :到目前为止,我只能检查字符串中是否包含单词,我不知道如何搜索数组,因此我可以在给定字符串中找到与数组中的单词匹配的单词。

Second Probelm 第二层

After first word if found on keyup, any other keyup runs the script whereas i want it to wait for another second match. 如果在keyup上找到第一个单词,则任何其他keyup都会运行脚本,而我希望它等待另一个第二次匹配。

CODE HERE 此处代码

$(document).on('keyup','.Post_TextArea',function(){
    post_val = $(this).val();
    if ($(this).val().length > 5){
        var string_g = 'tempo';
        var web_array = ['html', 'css', 'JavaScript'];
        var music_array = ['tempo', 'blues', 'rhythm'];
                if (post_val.toLowerCase().indexOf(string_g) >= 0){
                    if ($.inArray(string_g, web_array) !== -1){
                        $('.tags_holder').append('<span class="Tag_Style">Web</span>');
                    } else if ($.inArray(string_g, music_array) !== -1){
                        $('.tags_holder').append('<span class="Tag_Style">Music</span>');
                    } 
                    }
        }
    })

There are several things that you can do to solve your problem: 您可以执行以下几项操作来解决问题:

  • Create re-usable components 创建可重复使用的组件
  • Ensure each function does a single task 确保每个功能执行一项任务

Here's my take on the problem. 这是我对这个问题的看法。

Define your configuration 定义您的配置

We can create a taxonomy for categorizing your words. 我们可以创建一个分类法来对您的单词进行分类。 In this case, we can group the words in an array and classify them by the key. 在这种情况下,我们可以将单词分组到一个数组中,并通过键对其进行分类。

var taxonomy = {
    'web': ['html', 'css', 'javascript'],
    'music': ['tempo', 'blues', 'rhythm']
};

Defined your function 定义你的功能

Here we create two functions. 在这里,我们创建两个函数。 What we want to achieve are: 我们想要实现的是:

  • A predicate that checks for the word contained in the taxonomy 用于检查分类法中包含的单词的谓词
  • Function that returns the classification of the words 返回单词分类的函数

Below is a predicate to check if a word is contained within a wordList. 以下是检查wordList中是否包含单词的谓词。 We can use this with our check on whether or not a word is a 'tagged' word. 我们可以在检查单词是否为“标记”单词时使用它。

function contains(wordList) {
    return function(word) {
        return (wordList.indexOf(word) > -1);
    };
};

Below is a function that returns the list of tags of words from the input. 下面是一个函数,它从输入中返回单词标签列表。 The key to this is using the some() function, which should be more light weight than the filter() function. 这样做的关键是使用some()函数,该函数的重量应比filter()函数轻。

function getTags(input, taxonomy) {
    var words = input.match(/\w+/g);

    return Object.keys(taxonomy)
          .reduce(function(tags, classification) {
              var keywords = taxonomy[classification];
              if (words.some(contains(keywords)))
                  tags.push(classification);
              return tags;
          }, []);
};

Connect to jQuery 连接到jQuery

Now that we have the core code, we can connect this to jQuery. 现在我们有了核心代码,我们可以将其连接到jQuery。

$(function() {
    $('#input').on('keyup', function() {
        $('#tags').empty();
        var tags = getTags($(this).val(), taxonomy);
        tags.forEach(function(tag) {
            $('#tags').append($('<li>').text(tag));
        });
    });
});

Working Demo 工作演示

See this jsFiddle for a live demo. 观看此jsFiddle进行实时演示。 Note: this should work only on IE9+, as the some() , keys() , and forEach() functions are not support in IE < 9. 注意:这仅在IE9 +上有效,因为IE <9中不支持some()keys()forEach()函数。

I suggest you don't use a set of arrays, use a "map" instead - it's slightly less memory efficient but it's trivial to implement and very computationally efficient: 我建议您不要使用一组数组,而应使用“映射”-内存效率略低,但实现起来却微不足道,并且计算效率很高:

var tags = {
    'html': 'web', 'css': 'web', 'javascript': 'web',
    'tempo': 'music', 'blues': 'music', 'rhythm': 'music'
};

function suggestTags(input) {
    var result = { };
    var words = input.toLowerCase().split(/\s+/);
    words.forEach(function(word) {
        if (word in tags) {
            result[tags[word]]++;
        }
    }
    return Object.keys(result);
};

IMHO, an important point here is that the above is independent of any DOM manipulation. 恕我直言,这里的重点是,以上内容独立于任何DOM操作。 You'll get cleaner code by separating your word searching from your DOM logic. 通过将单词搜索与DOM逻辑分开,您将获得更简洁的代码。

NB: some of the above uses ES5 functions - use a "shim" to support them in older browsers if required. 注意:以上某些功能使用ES5功能-如果需要,请在较旧的浏览器中使用“垫片”来支持它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM