[javascript] Check whether a string matches a regex in JS

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.

This question is related to javascript regex match

The answer is


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


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');

try

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

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


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

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>

please try this flower:

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

true


_x000D_
_x000D_
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
_x000D_
_x000D_
_x000D_


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

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]

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");
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to match

How to test if a string contains one of the substrings in a list, in pandas? Delete rows containing specific strings in R Jquery Value match Regex How to compare two columns in Excel and if match, then copy the cell next to it Search File And Find Exact Match And Print Line? How to test multiple variables against a value? Selecting data frame rows based on partial string match in a column how to check if string contains '+' character PHP compare two arrays and get the matched values not the difference Check whether a string matches a regex in JS