Check whether a string matches a regex in JS
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
How to check if regex matches whole string in javascript?
You can either compare the length of the source to the match or compare the matched string to the source, if they are the same, you matched the entire string, and not just a part of it:
let source1 = "foo bar 12345";let source2 = "foo bar 12345 foo";
let match1 = source1.match(/foo bar \d+/);let match2 = source2.match(/foo bar \d+/);
console.log(match1[0] === source1);console.log(match1[0].length === source1.length);
console.log(match2[0] === source2);console.log(match2[0].length === source2.length);
how to check if string matches regex in javascript?
In javascript:
var inputString = '22-34';
var pattern = /\d{2}-\d{2}/;
var match = pattern.test(inputString); // match will equal true
MDN regular expression reference documentation
How to correctly check if a string match regex in javascript
/^"[^"]*"(?:\s*;\s*"[^"]*")+;?$/
---2---
---------3---------
-4
... can be broken down into ...
/^ ... $/
"[^"]*"
(?:\s*;\s*"[^"]*")+
;?
... which then translates to ...
- In between new line start and line end ...
- match a double quote, followed by an optional sequence of characters, each character not being a double quote, followed by a double quote.
- group
( ... )
the following match but do not capture it(?: ... )
and force this pattern to be present at least once(?: ... )+
... within this group ...- match the sequence of an optional whitespace (WS) a semicolon and another optional WS followed by the pattern already described with/under
(2)
.
- match the sequence of an optional whitespace (WS) a semicolon and another optional WS followed by the pattern already described with/under
- the entire match is allowed to end with none or exactly one semicolon.
const regex = /^"[^"]*"(?:\s*;\s*"[^"]*")+;?$/;
const test1 = `"hello"; "world";`;
const test1a = `"hello" ; "world" ;"world"; "world"`;
const test2 = `"hello" ; "world"`;
const test2a = `"hello";"world" ; "world";"world"`;
const test3 = `"hello; "world"`;
const test4 = `"hello"; world`;
const test5 = `"hello""world"`;
const test6 = `"hello ; world;";"hello ;world"`;
const test6a = `"hello ;world;" "hello; world"`;
const test6b = `"hello; world"`;
//should be true
console.log("test1", regex.test(test1));
console.log("test1a", regex.test(test1a));
console.log("test2", regex.test(test2));
console.log("test2a", regex.test(test2a));
console.log("test6", regex.test(test6));
//should be false
console.log("test3", regex.test(test3));
console.log("test4", regex.test(test4));
console.log("test5", regex.test(test5));
console.log("test6a", regex.test(test6a));
console.log("test6b", regex.test(test6b));
.as-console-wrapper { min-height: 100%!important; top: 0; }
regex.test V.S. string.match to know if a string matches a regular expression
Basic Usage
First, let's see what each function does:
regexObject.test( String )
Executes the search for a match between a regular expression and a specified string. Returns true or false.
string.match( RegExp )
Used to retrieve the matches when matching a string against a regular expression. Returns an array with the matches or
null
if there are none.
Since null
evaluates to false
,
if ( string.match(regex) ) {
// There was a match.
} else {
// No match.
}
Performance
Is there any difference regarding performance?
Yes. I found this short note in the MDN site:
If you need to know if a string matches a regular expression regexp, use regexp.test(string).
Is the difference significant?
The answer once more is YES! This jsPerf I put together shows the difference is ~30% - ~60% depending on the browser:
Conclusion
Use .test
if you want a faster boolean check. Use .match
to retrieve all matches when using the g
global flag.
Regex to check whether a string contains only numbers
var reg = /^\d+$/;
should do it. The original matches anything that consists of exactly one digit.
Javascript RegExp Check for Either String or Integer
var passVal = typeof(valueToMatch) === 'number'? valueToMatch.toString() : valueToMatch
var regExp = new RegExp(passVal , 'gi');
item.ssn.match(regExp)
You should check the value before passing through regex expression.
Test whether a string matches a regex?
you can use the test method in order to get the result as a Boolean
function isEqual(str){ return /\/users\/(.+)/.test(str); // code}
// Some examples of requests
console.log(isEqual('/users/1'));console.log(isEqual('/users/1/Nikita'));console.log(isEqual('/users'));
Fastest way to check a string contain another substring in JavaScript?
You have three possibilites:
Regular expression:
(new RegExp('word')).test(str)
// or
/word/.test(str)indexOf
:str.indexOf('word') !== -1
includes
:str.includes('word')
Regular expressions seem to be faster (at least in Chrome 10).
Performance test - short haystack
Performance test - long haystack
**Update 2011:**
It cannot be said with certainty which method is faster. The differences between the browsers is enormous. While in Chrome 10 indexOf
seems to be faster, in Safari 5, indexOf
is clearly slower than any other method.
You have to see and try for your self. It depends on your needs. For example a case-insensitive search is way faster with regular expressions.
Update 2018:
Just to save people from running the tests themselves, here are the current results for most common browsers, the percentages indicate performance increase over the next fastest result (which varies between browsers):
Chrome: indexOf (~98% faster) <-- wow
Firefox: cached RegExp (~18% faster)
IE11: cached RegExp(~10% faster)
Edge: indexOf (~18% faster)
Safari: cached RegExp(~0.4% faster)
Note that cached RegExp is: var r = new RegExp('simple'); var c = r.test(str);
as opposed to: /simple/.test(str)
Related Topics
Change Url Parameters and Specify Defaults Using JavaScript
Getting Value of Select (Dropdown) Before Change
How to Wait for Set of Asynchronous Callback Functions
Is Right Click a JavaScript Event
How to Share $Scope Data Between States in Angularjs Ui-Router
How to Get the Text Node of an Element
Issue in Returning Data Retrieved from Db Queries Called in the Loop
How to Refresh a Page Using JavaScript
Difference Between Microtask and MACrotask Within an Event Loop Context
How to Loop Through an Array Containing Objects and Access Their Properties
How to Pass JSON Post Data to Web API Method as an Object
Get String in Yyyymmdd Format from Js Date Object
What Is the JavaScript String Newline Character
Mongoose and Multiple Database in Single Node.Js Project
Addeventlistener Using for Loop and Passing Values