如何检查输入在 JavaScript 中是否有字符串

How to check an input has a string in JavaScript

我在 HTML 输入中有这个自动完成代码:

$("#myinput")
    .bind("keydown", function(event) {
        // don't navigate away from the field on tab when selecting an item
        if (event.keyCode === $.ui.keyCode.TAB 
                                   && $(this).data("autocomplete").menu.active) {
            event.preventDefault();
        }
    })
    .autocomplete({
        minLength: 0,
        source: function(request, response) {
            var results = [],
                selectionStart = this.element[0].selectionStart
                term = extractLast(request.term.substring(0, selectionStart));

                if (term.length > 0) {
                    console.log(term);
                if(/*input has string "where"*/)
                results = $.ui.autocomplete.filter(table1, term);
                else
                results = $.ui.autocomplete.filter(table2, term);   
            }
            response(results);
        },
        focus: function() {
            return false; // prevent value inserted on focus
        },
        select: function(event, ui) {
            var terms = split(this.value.substring(0, this.selectionStart));
            terms.pop();  // remove the current input
            terms.push(ui.item.value);        // add the selected item
            this.value = 
                $.trim(terms.join(" ") + this.value.substring(this.selectionStart)) + " ";
            return false;
        }
    });

我想做的是,如果输入在某个地方有字符串 "where",那么它将从 table1 加载自动完成,否则它将从 table2 加载。如何检查输入是否包含该字符串?提前致谢。

你应该使用 includes 方法。

var inputValue=$("#myinput").val();
if(inputValue.toLowerCase().includes("where")){
    //rest of code
}

另一种方法是使用indexOf方法。

if(inputValue.indexOf("where")!==-1){
    //rest of code
}

如果你想使用regex来完成这个成就,你可以使用search方法。

if(inputValue.search(/where/i)!==-1){
    //rest of code
}

inputValue="awherea";
console.log(inputValue.search(/where/))

如果你想要最强的浏览器支持,使用String#indexOf

if(this.value.indexOf('where') > -1) {
   //doSomething
}

您可以获得您的文本值并使用 indexof 找到它。

my_inp = $("#myinput").val();
if (my_inp.indexOf('where') > -1) {
   console.log('yes');
}

string#match method use the ternary operator 试试 return true 或 false

还有一些更多的方法

  1. string.indexOf()
  2. string.includes()

console.log('hello everyone'.match("hello") ? true : false)

对于 jquery 你可以使用 contains() 方法

console.log($('p').is(':contains("hi")')) 
console.log($('p').is(':contains("22")')) // not contains
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>hello hi</p>