Check whether a string matches a regex in JS

JavascriptRegexMatch

Javascript Problem Overview


I want to use JavaScript (can be with jQuery) to do some client-side validation to check whether a string matches the regex:

^([a-z0-9]{5,})$

Ideally it would be an expression that returned true or false.

I'm a JavaScript newbie, does match() do what I need? It seems to check whether part of a string matches a regex, not the whole thing.

Javascript Solutions


Solution 1 - Javascript

Use regex.test() if all you want is a boolean result:

console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false

console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true

console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true

...and you could remove the () from your regexp since you've no need for a capture.

Solution 2 - Javascript

Use test() method :

var term = "sample1";
var re = new RegExp("^([a-z0-9]{5,})$");
if (re.test(term)) {
    console.log("Valid");
} else {
    console.log("Invalid");
}

Solution 3 - Javascript

You can use match() as well:

if (str.match(/^([a-z0-9]{5,})$/)) {
    alert("match!");
}

But test() seems to be faster as you can read here.

Important difference between match() and test():

match() works only with strings, but test() works also with integers.

12345.match(/^([a-z0-9]{5,})$/); // ERROR
/^([a-z0-9]{5,})$/.test(12345);  // true
/^([a-z0-9]{5,})$/.test(null);   // false

// Better watch out for undefined values
/^([a-z0-9]{5,})$/.test(undefined); // true

Solution 4 - Javascript

Use /youregexp/.test(yourString) if you only want to know whether your string matches the regexp.

Solution 5 - Javascript

let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let regexp = /[a-d]/gi;
console.log(str.match(regexp));

Solution 6 - Javascript

Here's an example that looks for certain HTML tags so it's clear that /someregex/.test() returns a boolean:

if(/(span|h[0-6]|li|a)/i.test("h3")) alert('true');

Remember to indicate ^ for beginning of the string and $ for the end, if you want to test the exact match of entire string.

Example:

/[a-z]+/.test('aaa111'); // true
/^[a-z]+$/.test('aaa111'); // false

Solution 7 - Javascript

const regExpStr = "^([a-z0-9]{5,})$"
const result = new RegExp(regExpStr, 'g').test("Your string") // here I have used 'g' which means global search
console.log(result) // true if it matched, false if it doesn't

Solution 8 - Javascript

try

 /^[a-z\d]{5,}$/.test(str)

console.log( /^[a-z\d]{5,}$/.test("abc123") );

console.log( /^[a-z\d]{5,}$/.test("ab12") );

Solution 9 - Javascript

I would recommend using the execute method which returns null if no match exists otherwise it returns a helpful object.

let case1 = /^([a-z0-9]{5,})$/.exec("abc1");
console.log(case1); //null

let case2 = /^([a-z0-9]{5,})$/.exec("pass3434");
console.log(case2); // ['pass3434', 'pass3434', index:0, input:'pass3434', groups: undefined]

Solution 10 - Javascript

You can try this, it works for me.

 <input type="text"  onchange="CheckValidAmount(this.value)" name="amount" required>

 <script type="text/javascript">
    function CheckValidAmount(amount) {          
       var a = /^(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$/;
       if(amount.match(a)){
           alert("matches");
       }else{
        alert("does not match"); 
       }
    }
</script>

Solution 11 - Javascript

please try this flower:

/^[a-z0-9\_\.\-]{2,20}\@[a-z0-9\_\-]{2,20}\.[a-z]{2,9}$/.test('[email protected]');

> true

Solution 12 - Javascript

If you don't want ^ and $ around the regex (I had such a usecase) you can do something like

let reg = /[a-zA-Z0-9]+/g
let txt = "hello"
let matches = reg.exec(txt)[0] == txt
console.log(`It ${matches ? "does" : "doesn't"} match`)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRichardView Question on Stackoverflow
Solution 1 - Javascriptuser113716View Answer on Stackoverflow
Solution 2 - JavascriptAbhijeet KasurdeView Answer on Stackoverflow
Solution 3 - JavascriptpmrotuleView Answer on Stackoverflow
Solution 4 - Javascriptuser278064View Answer on Stackoverflow
Solution 5 - JavascriptMikeView Answer on Stackoverflow
Solution 6 - Javascriptuser2449231View Answer on Stackoverflow
Solution 7 - JavascriptGeetanshu GulatiView Answer on Stackoverflow
Solution 8 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 9 - JavascriptJuan NavarreteView Answer on Stackoverflow
Solution 10 - JavascriptTongiView Answer on Stackoverflow
Solution 11 - JavascriptJaber AlshamiView Answer on Stackoverflow
Solution 12 - JavascriptMadhusoodan PView Answer on Stackoverflow