我如何搜索正则表达式javascript随机

How can i search regex javascript randomly?

本文关键字:正则表达式 javascript 随机 搜索 何搜索      更新时间:2023-09-26

我试图实现搜索我的webapp,但不知何故正则表达式不能正常工作。作为标志我有I,m和g

标记:

<form role="form">
    <input type="text" id="search" placeholder="Search...." />
 </form>

脚本:

 $('#search').keyup(function(){
     var searchFieldValue = $('#search').val(),
         re = new RegExp(searchFieldValue, "img"),
         str = "The sky is awake so I am awake so we have to play";
     if ( str.search(re) == -1 ){
         console.log("Does not contain " + searchFieldValue );
     }else{
         console.log("Contains " + searchFieldValue);
     }
 });
<标题> 演示

问题:

输入The sky is awake将返回true

但是输入we have to play the将返回falsewe have the sky we将返回false

我怎么能解决这个问题,因为we have the sky是str的一部分(不作为索引,但所有单个单词都在str中)

我想要什么:

I want that if each and all words are in the str then return true no matter the index of each words

谢谢!

使用现代浏览器,我能看到的最简单的方法是:

$('#search').keyup(function (e) {
    // we're splitting on the white-space characters, therefore they don't
    // seem a useful character to run this function on:
    if (e.which !== 32) {
        var searchFieldValue = $('#search').val(),
            str = "The sky is awake so I am awake so we have to play",
            // splitting the searchFieldValue on white-space (to get
            // individual words):
            words = searchFieldValue.split(/'W+/),
            // using Array.prototype.every() to check that each word entered
            // is present in the string; `every()` will return a Boolean,
            // true: every element in the array returned true for the condition,
            // false: one, or more, element(s) returned false for the condition:
            allPresent = words.every(function (a) {
            // creating a new Regular Expression for each word
            // in order to apply your own approach:
            return str.search(new RegExp(a, 'img')) > -1;
        });
        // just for diagnostic purposes:
        console.log(allPresent);
        // you could, of course, omit the variable and simply return
        // the words.every(function(a){...});
        return allPresent;
    }
});

JS Fiddle demo.

稍微便宜一点的方法(避免创建多个正则表达式对象):

$('#search').keyup(function (e) {
    if (e.which !== 32) {
        var searchFieldValue = $('#search').val(),
            str = "The sky is awake so I am awake so we have to play",
            words = searchFieldValue.split(/'W+/),
            allPresent = words.every(function (a) {
            // finding the lowercased word inside of the lowercased string:
            return str.toLowerCase().indexOf(a.toLowerCase()) > -1;
        });
        console.log(allPresent);
        return allPresent;
    }
});

JS Fiddle demo.

根据OP的评论编辑:

[让我们]说[那]我有一个[字符串]'awakeness'有一个正则表达式到return false当用户[输入]'awake'只?

是的,但是这涉及到使用更昂贵的多重regexp解决方案:

$('#search').keyup(function (e) {
    if (e.which !== 32) {
        var searchFieldValue = $('#search').val(),
            str = "awakeness",
            words = searchFieldValue.split(/'W+/),
            allPresent = words.every(function (a) {
            // the change is the following line, which matches word-boundaries:
            return str.search(new RegExp("''b" + a + "''b", 'img')) > -1;
        });
        console.log(allPresent);
        return allPresent;
    }
});

JS Fiddle demo.

引用:

  • Array.prototype.every() .
  • JavaScript正则表达式。
  • String.split() .
  • String.toLowerCase() .

将字符串分成单词并检查每个单词:

jsfiddle更新

$('#search').keyup(function(){
    var searchFieldValue = $('#search').val();
    var searchedWords = searchFieldValue.split(' ');
    var contains = []; var notContains = [];
    for(var i in searchedWords){
        var re = new RegExp(searchedWords[i], "gim");
        var str = "The sky is awake so I am awake so we have to play";
        str.search(re) == -1 ? notContains.push(searchedWords[i]): contains.push(searchedWords[i]);
    }
    console.clear();
    var resStr = str;
    if( !notContains.join(' ') )
        for(var i in contains) resStr = resStr.replace(contains[i],'');
    console.log('Words not typed yet: '+resStr);
    console.log('is everything typed: '+!resStr.trim().length);
    console.log('is everything typed an nothing more: '+(!resStr.trim().length && contains.length >= str.split(' ').length));

    console.log("Each and all words are "+(!notContains.join(' ')?'':'not all ')+"in the str.");
    console.log("Does contain: ",contains.join(' ') );
    console.log("Does not Contain: "+notContains.join(' '));
});