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

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

javascript - Allow only digits and a specific word in jQuery

I need to write regular expression (or a test using jQuery) that allows only digits and a specific word.

For example (the word "Hello" is allowd):

  • 123Hello => valid
  • hello => valid
  • 123 => valid
  • hello word => invalid
  • he123llo => invalid
  • he llo 123 => invalid

Thank you in advance

question from:https://stackoverflow.com/questions/65843241/allow-only-digits-and-a-specific-word-in-jquery

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

1 Answer

0 votes
by (71.8m points)

If I understand correctly, the following simple pattern should work for you:

^d*(?:hello)?d*$

You may use the regex in case insensitive mode. Example:

var inputs = ["123Hello", "hello", "123", "hello word", "he123llo", "he llo 123"];
inputs.forEach(function(input) {
    if (/^d*(?:hello)?d*$/i.test(input)) {
        console.log(input + ": VALID");
    }
    else {
        console.log(input + ": INVALID");
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...