1138

I want to use JavaScript (I can also use jQuery) to do check whether a string matches the regex ^([a-z0-9]{5,})$, and get a true or false result.

match() seems to check whether part of a string matches a regex, not the whole thing. Does it solve the problem? Can I adapt it to solve the problem? How?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Richard
  • 31,629
  • 29
  • 108
  • 145
  • 1
    Do you want a complete match, or just whether the string _contains_ a matching substring? – Kerrek SB Jul 06 '11 at 21:12
  • 2
    A complete match - not a matching substring. – Richard Jul 06 '11 at 21:13
  • I'm confused by how the problem was originally posed. Sure, `match` doesn't require the entire string to match the regex. But the `^` and `$` anchors ensure that **this regex** can **only possibly** match against the entire string - that's their **purpose**. – Karl Knechtel Jan 09 '23 at 23:48
  • 1
    Anyway, relevant documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions – Karl Knechtel Jan 09 '23 at 23:48

15 Answers15

1749

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.

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
user113716
  • 318,772
  • 63
  • 451
  • 440
258

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");
}
KeaganFouche
  • 581
  • 5
  • 12
Abhijeet Kasurde
  • 3,937
  • 1
  • 24
  • 33
143

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
pmrotule
  • 9,065
  • 4
  • 50
  • 58
  • 3
    The reason it works with a number is because the number is coerced into a string, because it's given as a parameter when it's expecting a string. I wouldn't rely on this behavior. It depends on your environment's implementation of test(). (match fails because numbers don't have a `match` member). I'd reccomend explicitly converting your number to a string if you want to use it with a regex (`String(123)` for example). – Bronzdragon Jan 20 '19 at 14:47
  • The match can be used here, but if you look at performance, `test` performs 30% better when we just want to validate a string to match the regex and not extract substrings from it. – Akansh Feb 26 '19 at 06:19
  • @pmrotule Yeah, but it should be mentioned before match description. – Akansh Feb 26 '19 at 10:54
  • The most significant difference between test and match (and matchAll) is that match does things like to return a list of all matching sub-strings, while test only checks if there are any. Check the regex methods in https://javascript.info/regexp-methods – Juan Lanus Jan 13 '20 at 20:49
  • @Bronzdragon this answer claims that it doesn't work with `match`, even though `match` would be called the same way. Why would the same coercion not occur there? – Karl Knechtel Jan 09 '23 at 23:50
  • @KarlKnechtel Because `match` is not a prototype function of `Number`, you would need to convert it to a string first. – pmrotule Jan 10 '23 at 07:51
  • The same coercion *can* happens if `.match()` were to be called with `.call()`: `String.prototype.match.call(12345, /^([a-z0-9]{5,})$/)` – InSync May 29 '23 at 18:37
62

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

J0e3gan
  • 8,740
  • 10
  • 53
  • 80
user278064
  • 9,982
  • 1
  • 33
  • 46
25

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
Kostanos
  • 9,615
  • 4
  • 51
  • 65
user2449231
  • 554
  • 6
  • 6
23

let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let regexp = /[a-d]/gi;
console.log(str.match(regexp));
dota2pro
  • 7,220
  • 7
  • 44
  • 79
Mike
  • 458
  • 4
  • 13
12

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
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Geetanshu Gulati
  • 692
  • 8
  • 13
7

try

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

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

console.log( /^[a-z\d]{5,}$/.test("ab12") );
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
7

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]
Juan
  • 477
  • 4
  • 8
6

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>
Tongi
  • 127
  • 1
  • 1
4

please try this flower:

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

true

Jaber Alshami
  • 336
  • 3
  • 14
2

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`)
Madhusoodan P
  • 681
  • 9
  • 20
1

Update/Add

If the query string does not present in the URL then the below solution will work to add the param in the URL, if it already exists then it will update.

function updateUrlParameter(url, param, value) {
  var regex = new RegExp("(?<=[?|&])(" + param + "=)[^&]+", "i");
  if (regex.test(url)) {
    return url.replace(regex, param + "=" + value);
  } else {
    if (window.location.search) {
      return `${url}&${param}=${value}`;
    }else{
      return `${url}?${param}=${value}`;
    }
  }
}

Sufiyan Ansari
  • 1,780
  • 20
  • 22
0

Calling RegExp.prototype.test() is probably correct, but has a couple caveats:

  • It will tell you whether a string "matches" a regex -- i.e. if it "contains a matching sequence" -- not whether the string is an "exact match".
  • If a regex is global /g it actually stores state, from the MDN:

JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g., /foo/g or /foo/y). They store a lastIndex from the previous match... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

This means, for the first point, you need to use anchors, where ^ indicates the start of a string, and $ indicates it's end. So a regex matching the full string "Cat" & nothing else would be: /^Cat$/

And secondly, you cannot reuse regex.test(str) with a global regex on the same string for this purpose, as it's meaning changes over time. E.g. (and note the failure, despite using different instances of string)

reg = /t/g;
console.log(reg.lastIndex); // 0 -- Never run
console.log(reg.test("Cat")); // true -- Matched "t"
console.log(reg.lastIndex); // 3 -- 3rd character was "t"
console.log(reg.test("Cat")); // false -- no more matches!
Lovethenakedgun
  • 731
  • 6
  • 22
0

match() seems to check whether part of a string matches a regex, not the whole thing. Does it solve the problem? Can I adapt it to solve the problem? How?

Yes, you can. ^ and $ are not needed if you so choose.

The idea is simple: .match() returns a "match" array. If the first element (i.e. the whole match, or $0) equals to the string, then we have a full match.

function fullMatch(string, regex) {
  const match = string.match(regex);
  return match?.[0] === string;
}

Try it:

console.config({ maximize: true });

function fullMatch(string, regex) {
  const match = string.match(regex);
  console.log(match);
  return match?.[0] === string;
}

const string = 'f00bar';
const testcases = [
  /\d+c?ba/, // false
  /f\d+\w+/, // true
  /[0a-z]+/g // false
];

testcases.forEach(
  regex => console.log(fullMatch(string, regex))
);
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Note that this does not work with g regexes, as this flag causes .match() to always return a normal array if there is at least one match.

You can, however, use RegExp#exec() instead:

function fullMatch(string, regex) {
  const match = regex.exec(regex);
  return match?.[0] === string;
}

Try it:

console.config({ maximize: true });

function fullMatch(string, regex) {
  const match = regex.exec(string);
  console.log(match);
  return match?.[0] === string;
}

const string = 'f00bar';
const testcases = [
  /\d+c?ba/, // false
  /f\d+\w+/, // true
  /[0a-z]+/g // true
];

testcases.forEach(
  regex => console.log(fullMatch(string, regex))
);
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

One-liner:

const fullMatch = (string, array) => regex.exec(string)?.[0] === string;
InSync
  • 4,851
  • 4
  • 8
  • 30