Javascript RegEx Not Working [duplicate] - javascript

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 2 years ago.
I have the following javascript code:
function checkLegalYear() {
var val = "02/2010";
if (val != '') {
var regEx = new RegExp("^(0[1-9]|1[0-2])/\d{4}$", "g");
if (regEx.test(val)) {
//do something
}
else {
//do something
}
}
}
However, my regEx test always returns false for any value I pass (02/2010). Is there something wrong in my code? I've tried this code on various javascript editors online and it works fine.

Because you're creating your regular expression from a string, you have to double-up your backslashes:
var regEx = new RegExp("^(0[1-9]|1[0-2])/\\d{4}$", "g");
When you start with a string, you have to account for the fact that the regular expression will first be parsed as such — that is, as a JavaScript string constant. The syntax for string constants doesn't know anything about regular expressions, and it has its own uses for backslash characters. Thus by the time the parser is done with your regular expression strings, it will look a lot different than it does when you look at your source code. Your source string looks like
"^(0[1-9]|1[0-2])/\d{4}$"
but after the string parse it's
^(0[1-9]|1[0-2])/d{4}$
Note that \d is now just d.
By doubling the backslash characters, you're telling the string parser that you want single actual backslashes in the string value.
There's really no reason here not to use regular expression syntax instead:
var regEx = /^(0[1-9]|1[0-2])\/\d{4}$/g;
edit — I also notice that there's an embedded "/" character, which has to be quoted if you use regex syntax.

Related

Convert string into Regular Expression in Javascript [duplicate]

This question already has answers here:
Building regexp from JS variables not working
(5 answers)
Closed 7 years ago.
From the backend of my application, I receive a regular expression which should be matched with a postal code in the frontend.
However, every time I convert to string into a regular expression using the RegExp class, I get another regular expression which doesn't match my postal code anymore.
This is the code I'm currently using (copy from my console):
var str = '/^[1-9][0-9]{3}\s?([a-zA-Z]{2})?$/',
exp = new RegExp(str);
// Returns null
'1055AA'.match(exp);
// The code below does work though...
// Returns: ["1055AA", "AA"]
'1055AA'.match(/^[1-9][0-9]{3}\s?([a-zA-Z]{2})?$/);
Can someone help me solve this problem? Thanks!
Your input string must not begin and end with the Regexp markers / - after all, it's a regular string, not a literal regexp. Also, since it's a regular string (and not (yet) a regexp), you need to double the backslashes as usual in a regular string.

same dynamic regex and inline regex not giving same output in javascript [duplicate]

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 7 years ago.
I have been staring at these two flavors of same regex and can't figure out why the outcome is different:
var projectName="SAMPLE_PROJECT",
fileName="1234_SAMPLE_PROJECT",
re1 = new RegExp('^(\d+)_SAMPLE_PROJECT$','gi'),
re2 = /^(\d+)_SAMPLE_PROJECT$/gi,
matches1 = re1.exec(fileName),
matches2 = re2.exec(fileName);
console.log(matches1);//returns null
console.log(matches2);//returns correctly
Here is the jsbin : https://jsbin.com/badoqokumu/edit?html,js,output
Any idea what I must be doing wrong with instantiating RegExp?
Thanks.
In the first case, you have a string literal, which uses \ to introduce escape sequences. \d in a string is just d. If you want \d, you need to type \\d instead.
In the second case, you have a regular expression literal, which does not interpret \ as a string escape sequence.

Backslash Discrepancy between Regex Constructor and Literals [duplicate]

This question already has an answer here:
javascript why double escape dot/character [closed]
(1 answer)
Closed 7 years ago.
The title sums it up. I came across an odd discrepancy in backslash escaping between regular expression literals and constructor functions with new RegExp(), and I was curious about what's behind it.
I was trying to escape a parenthesis ( inside a constructor, like so:
var search = new RegExp('/(', 'g');
var result = "(test)".match(search);
But this kept returning an error. The match worked fine inside a literal /\(/g;, but inside the constructor I ended up having to do something like this:
search = new RegExp('\\(', 'g');
Can someone please explain to me why an escaping backslash requires an escaping backslash itself in a constructor, but not a literal?
Because the backslash is a special character in both the context of a regexp, and the context of a string literal. You have to get past the string literal's special usage before the regexp parser can see it and apply its own special rules.
NOTE If pattern is a StringLiteral, the usual escape sequence substitutions are performed before the String is processed by RegExp. If pattern must contain an escape sequence to be recognised by RegExp, any backslash \ characters must be escaped within the StringLiteral to prevent them being removed when the contents of the StringLiteral are formed.
http://www.ecma-international.org/ecma-262/5.1/#sec-15.10.4.1

Javascript: Escaping character issue in a string for RegExp? [duplicate]

This question already has answers here:
JavaScript Regex, where to use escape characters?
(3 answers)
Closed 8 years ago.
I am having a small issue with placing a RegExp pattern inside a string, I have 2 patterns which are both really the same. The first doesn't work I presume due to the \d - is it being seen as an escape character?
var pattern = '^.{1,5}-\d{1,5}$'; // Doesn't work
var pattern = '^[a-zA-Z]{1,5}-[0-9]{1,5}$'; // Works
Is there anyway around this ? apart from replacing the \d with [0-9]?
Here is the extra code I am using
var regex = new RegExp(pattern);
var result = regex.test(value);
Thanks in advance
As found in the documentation you have several different ways to create a RegExp
Regular expression literal,
var regex = /^.{1,5}-\d{1,5}$/;
Constructor function of the RegExp object
var regex = new RegExp("^.{1,5}-\\d{1,5}$");
since it is a string, you need to escape any \
Same for \w and other backslashed chars
The second version is mostly used if you have variables you need to add to the regexp
If you want the way your are writing the regex to work, you can double escape the d:
var pattern = '^.{1,5}-\\d{1,5}$'; // Should work
var regex = new RegExp(pattern);
Otherwise, you can use the regex directly using the delimiters /:
var pattern = /^.{1,5}-\d{1,5}$/;
In the first instance, you are storing the pattern in a string, and the actual characters that are being passed to the variables are: ^.{1,5}-\d{1,5}$ because \d has no meaning in a string, but \\d is a backslash and a literal d. You can try putting a backslash in a string:
console.log('\'); // Won't run
console.log(' \ '); // Returns a space
console.log('\n'); // Returns a newline character
So that if you mean a literal backslash, you have to escape it.
Using:
var pattern = '^.{1,5}-\\d{1,5}$'; // Should work
var regex = new RegExp(pattern);
should be faster though, if you are using the regex several times, because here, you are compiling the regex so that you can use it multiple times.
The other way will require compiling the regex each time it is called for.

JavaScript regex for string literal? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a RegExp.escape function in Javascript?
I'm currently using: var keywords = new RegExp(req.params.keywords, 'i');
The catch is, if req.params.keywords == '.*', this will match anything, what I want is for it to match .* literally, as in \.\*\
Is there a more elegant solution than escaping every passed single character with a \?
If you want to match literally, instead of using the regular expressions included in the string, don't use a regular expression. Use the string indexOf() function to see if a string is contained withing another one.
For case insensitive matching, you convert each string to, say, lower case before the match.
var searchForString = req.params.keywords.toLowerCase();
var searchInString = xxx.toLowerCase();
if (searchInString.indexOf(searchForString) >= 0) {
... then it matches ...
}

Categories

Resources