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.
W3Schools
w3schools.com › jsref › jsref_match.asp
JavaScript String match() Method
The search() method returns the position of the first match. ... Regular Expression Search and Replace can be done with different methods. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
Top answer 1 of 15
1847
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.
2 of 15
271
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");
}
Regular Expressions test() - match()? Are these used interchangeably?
Jonathan Grieve is having issues with: Just a quick question to help clear up some confusion. Joel mentions the match() method but seems to use the test() method in its place.... More on teamtreehouse.com
[Javascript]String match with regex gives weird results
Read through the description section of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match - essentially .match() behaves differently if you use the /g flag. Also your use of ";?" at the end of the regex won't do anything, the "(.+)" before it will greedily match to the end of the string. I'm curious what you're trying to do here, and why we're parsing JavaScript commands in a regular expression in the first place. More on reddit.com
Regexp match only integers, ignore floats and other characters.
str.split(",").filter(x => Number.isInteger(Number(x)));
Should be faster than regex.
*Edited to include cast to Number since isInteger is false for strings
More on reddit.comRegex- How to Match Parentheses
Something like this? https://regex101.com/r/rH0zB0/1 More on reddit.com
Videos
An Easy Way to Do Regex - JavaScript String Match (In 2 Mins)
01:00
How to use regex to check if a javascript string contains a pattern ...
04:23
JavaScript Regex Tutorial: Mastering the match() Method for Pattern ...
17:16
Regular Expressions (Regex) in JavaScript - tutorial - YouTube
02:35
JavaScript Regular Expressions: Match Beginning String Patterns ...
17:55
RegExp - regex // JavaScript Regular Expressions Ultimate MasterClass ...
freeCodeCamp
freecodecamp.org › news › javascript-regex-match-example-how-to-use-the-js-replace-method-on-a-string
JavaScript Regex Match Example – How to Use JS Replace on a String
January 4, 2021 - In this case, we .match() an array with the first match along with the index of the match in the original string, the original string itself, and any matching groups that were used. But say you want to see how many times the word "are" occurs in a string. To do that, just add the global search flag to your regular expression: const csLewisQuote = 'We are what we believe we are.'; const regex = /are/g; csLewisQuote.match(regex); // ["are", "are"]
Medium
medium.com › nerd-for-tech › basics-of-javascript-string-match-method-ce47295bfd97
Basics of Javascript · String · match() (method) | by Jakub Korch | Nerd For Tech | Medium
June 9, 2021 - That's...", // length: 0 // ]regExp.exec(str) // [ // "ain", // groups: undefined, // index: 5, // input: "The main bulk of rain will fall in SPAIN. That's...", // length: 0 // ](str.match(regExp))[0] // ain · First case uses regular expressions searching for the string “ain” with the additional flag “g” which specifies that we want to find all the matches.
CodingNomads
codingnomads.com › match-string-javascript
JavaScript String Matching
The first one uses the forward slash notation, and the second one uses the RegExp constructor. The second one is a bit more complicated, though, because you need to escape the backslashes. This is because the backslash is a special character in JavaScript strings, so you need to escape it with another backslash. You can also pass a normal string to the .search() and .match() methods where it will get automatically converted into a RegExp object.
Honeybadger
honeybadger.io › blog › javascript-regular-expressions
The ultimate JavaScript regex guide - Honeybadger Developer Blog
May 9, 2025 - The code above creates a simple regex pattern that will result in a JavaScript regex match for the first occurrence of the exact text "Hello". This notation is used when you know how the pattern will look when writing the code. Note: You don't need to enclose the patterns in single or double quotes; you can add flags after the closing forward slash. JavaScript has a RegExp constructor that you can use to create regex patterns. You pass the pattern as a string argument to the constructor:
Reddit
reddit.com › r/learnprogramming › [javascript]string match with regex gives weird results
r/learnprogramming on Reddit: [Javascript]String match with regex gives weird results
October 12, 2015 -
As I understand it, .match is supposed to return only matched groups, and would be the thing to use for "global" matches, so I'm doing just that to get variable names and their definitions from the code of a function. However...
var str = "function startMidiMusic(s) { popBox = window.open(s,'midi','scrollbars=no,resizable=no,width=250,height=125,left=10,top=10'); popBox.focus(); foo = 'bar';}";
//Gets an extraneous thing and only the first result
str.match(/(\S+) ?= ?(.+);?/);
>> Array [ "popBox = window.open(s,'midi','scro…", "popBox", "window.open(s,'midi','scrollbars=no…" ]
//Only gets a portion of the "original" string
str.match(/(\S+) ?= ?(.+);?/g);
>> Array [ "popBox = window.open(s,'midi','scro…" ]
None of them include "foo" and "bar", let alone in the way I'm expectingWhat's going on?
Top answer 1 of 2
1
Read through the description section of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match - essentially .match() behaves differently if you use the /g flag. Also your use of ";?" at the end of the regex won't do anything, the "(.+)" before it will greedily match to the end of the string. I'm curious what you're trying to do here, and why we're parsing JavaScript commands in a regular expression in the first place.
2 of 2
1
Well, the first thing of note is that your regex doesn't quite seem correct. Assuming you wanted to capture the name of the variable being assigned to and the value it's given, we can't use .+, since that would consume the ; that marks the end of the value (and thus we'd end up consuming too much) Instead, we'd have to use a group containing all valid characters we'd want to consume (which is pretty much everything not a ;). /(\S+) ?= ?([^;]+);?/ An alternative would be to use lazy matching for something that must end with a semicolon: /(\S+) ?= ?(.+?;)/ The laziness there is crucial. It ensures it tries to match as little as possible, and thus stops matching at that first semicolon. Of course, both approaches still fail if there's a semicolon inside a string. You can't parse JS with regex! But I'll assume you're aware of this limitation and are okay with the approximate results. In this case, the returned value is: The match made: "popBox = window.open(s,'midi','scrollbars=no,resizable=no,width=250,height=125,left=10,top=10');" The two capture groups: "popBox" and ""window.open(s,'midi','scrollbars=no,resizable=no,width=250,height=125,left=10,top=10')". In case it wasn't obvious, the … is the browser's console truncating a long string. Access the array element itself to see the full string. That's presumably why you think you're only getting a portion of the original string. You actually got it all, but it wasn't all shown.
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › match
String.prototype.match() - JavaScript | MDN
The match() method of String values retrieves the result of matching this string against a regular expression. const paragraph = "The quick brown fox jumps over the lazy dog. It barked."; const regex = /[A-Z]/g; const found = paragraph.match(regex); console.log(found); // Expected output: Array ...
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Regular_expressions
Regular expressions - JavaScript | MDN
For instance, to match the string "C:\" where "C" can be any letter, you'd use /[A-Z]:\\/ — the first backslash escapes the one after it, so the expression searches for a single literal backslash. If using the RegExp constructor with a string literal, remember that the backslash is an escape ...
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-match-multiple-parts-of-a-string-using-regexp-in-javascript
JavaScript - How to Match Multiple Parts of a String Using RegExp? - GeeksforGeeks
July 23, 2025 - Non-capturing groups (?:...) allow you to combine multiple patterns without creating separate capturing groups. This is useful when you need to match multiple patterns in a string but don’t need to extract the individual parts. ... let s = "apple123 orange456 apple789"; let regex = /(?:apple|orange)\d+/g; let res = s.match(regex); console.log(res);
W3Schools
w3schools.com › js › js_regexp.asp
JavaScript Regular Expressions
JavaScript RegExp is an Object for handling Regular Expressions. ... let text = "Visit Microsoft!"; let result = text.replace(/Microsoft/i, "W3Schools"); Try it Yourself » ... In a regular expression an alternation is denoted with a vertical line character |. An alternation matches any of the ...
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › RegExp › test
RegExp.prototype.test() - JavaScript | MDN
Using this internally, test() can be used to iterate over multiple matches in a string of text (with capture groups). const str = "table football"; const regex = /fo+/; const globalRegex = /fo+/g; console.log(regex.test(str)); // Expected output: true console.log(globalRegex.lastIndex); // Expected output: 0 console.log(globalRegex.test(str)); // Expected output: true console.log(globalRegex.lastIndex); // Expected output: 9 console.log(globalRegex.test(str)); // Expected output: false
RegExr
regexr.com
RegExr: Learn, Build, & Test RegEx
Supports JavaScript & PHP/PCRE RegEx. Results update in real-time as you type. Roll over a match or expression for details.
Regex101
regex101.com
regex101: build, test, and debug regex
Regular expression tester with syntax highlighting, explanation, cheat sheet for PHP/PCRE, Python, GO, JavaScript, Java, C#/.NET, Rust.
Eloquent JavaScript
eloquentjavascript.net › 09_regexp.html
Regular Expressions :: Eloquent JavaScript
This code takes a string, finds all occurrences of a number followed by an alphanumeric word, and returns a string that has one less of every such quantity. The (\d+) group ends up as the amount argument to the function, and the (\p{L}+) group gets bound to unit. The function converts amount to a number—which always works, since it matched \d+ earlier—and makes some adjustments in case there is only one or zero left. We can use replace to write a function that removes all comments from a piece of JavaScript code.