Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to find if what the user typing in to an input field contain certain text - I've kinda got it works, but only working for an exact match as opposed to a partial match. If a user types anything before the text i'm matching, of course the code doesn't trigger.

What i need to do is check if the input contains @nyu.edu at all in the input field.

$('.email').keyup(function(){
    if ($(".email").val() == "@nyu.edu") {
        $("p.warning").css("visibility", "visible");
    }
    else if ($(".email").val() != "@nyu.edu") {
        $("p.warning").css("visibility", "hidden");
    }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
479 views
Welcome To Ask or Share your Answers For Others

1 Answer

Checking if a string contains a substring is pretty easily done by taking haystack.indexOf(needle) and checking against -1 (not found).

if ($(".email").val().indexOf("@nyu.edu") !== -1) {
    // contains
} else {
    // does not contain
}

There is a function in the ES6 draft which you may find more natural, called includes

You can add support for ES6's String.prototype.includes like this

if (!String.prototype.includes) {
    String.prototype.includes = function (needle, pos) {
        return this.indexOf(needle, pos || 0) !== -1;
    };
}

"foobar".includes('foo'); // true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...