Javascript regex ignoring backslash period requirement [duplicate] - javascript

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 2 years ago.
For my regex:
^(http(s)?\://)?(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$
I am wondering as to why "john" passes? This regex is only supposed to pass for URLs
> var j = new RegExp("^(http(s)?\://)?(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$");
> j.test("john")
> true
There is a required \. within the regex line

You are constructing your regular expression by passing a string to the RegExp constructor function.
While \ has special meaning as an escape character in regular expressions, it also has a similar meaning in string literals.
The \\ in the string literal has been parsed into \ in the string and thus is treated as an escape character in the regular expression.
You need to provide an escaped \ and and escaped escape character.
So for a regular expression that matches a single \ you need:
var myRegEx = new RegExp("\\\\")
I suggest avoiding the constructor function and using a regex literal instead.
var myRegEx = /\\/;

Related

How to match with new RegExp exactly [duplicate]

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 5 years ago.
I have this string:
var str = "https://www.mysite.se/this-match?ba=11"
I need to match it exactly (between / and ?), so only this-match matches, not this-ma or anything (shorter) that is contained in this-match.
I.e:
var myre = new RegExp('\/this-ma\?');
Still matches:
myre.exec(str)[0]
"/this-ma"
How can I avoid that a shorter string contained in this-match does give a match?
The definition of your regex is wrong. You'd think that \? would match literal ? character, instead of being non-greedy modifier. Not true. Quite the opposite, in fact.
var myre = new RegExp('\/this-ma\?');
> /\/this-ma?/
The backslash here works within the string literal, and outputs single ? to regex, which becomes non-greedy modifier. Use the regex literal.
var myre = /\/this-ma\?/

Matching the string "/$" in a RegExp constructor [duplicate]

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 6 years ago.
I'm trying to match the phrase "/$" using the RegExp constructor, but no amount of escaping seems to help. Am is missing something?
RegExp("\/\$").test("/$")
// false
RegExp("/$").test("/$")
// false
RegExp("\/$").test("/$")
// false
RegExp("/\$").test("/$")
// false
You need to use \\ instead of \ and there is no need to escape / or use regex /\/\$/ directly. Check RegExp documentation for more info.
When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.
For example, /\w+/ is equivalent to new RegExp('\\w+')
console.log(
RegExp("/\\$").test("/$")
)
//or
console.log(
/\/\$/.test("/$")
)
Refer : Javascript regular expression - string to RegEx object

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.

Categories

Resources