using RegExp constructor result into wrong output [duplicate] - javascript

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 4 years ago.
I have a regex expression which i use for email address validation. It is working fine as literal expression but showing different result when using the RegExp constructor.
var emailpattern=/^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/g;
console.log(emailpattern.test('nithin#gmail.com'))//true
var obj = new RegExp('^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$','g');
console.log(obj.test('nithin#gmail.com'))//false

You need to remove quotes for the pattern which you have specified in the new RegExp() to get rid of extra overhead of escaping the \ character:
var emailpattern=/^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/g;
console.log(emailpattern.test('nithin#gmail.com'))//true
var obj = new RegExp(/^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,'g');
console.log(obj.test('nithin#gmail.com'))//false
Escaping the \ character:
var emailpattern=/^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/g;
console.log(emailpattern.test('nithin#gmail.com'))//true
var obj = new RegExp('(([^<>()\\[\\]\\\.,;:\s#"]+(\\.[^<>()\\[\\]\\\.,;:\\s#"]+)*)|(".+"))#((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))','g');
console.log(obj.test('nithin#gmail.com'))//false

Related

String starting with backslash hacks my regex [duplicate]

This question already has answers here:
How can I use backslashes (\) in a string?
(4 answers)
Closed 3 years ago.
My string should be in the IRC command format : "/add john".
So, i created this Regex :
var regex = /^\/add ([A-Za-z0-9]+)$/
var bool = regex.test('\/add user1');
alert(bool);
The problem is either I use /***/ or RegExp syntax, if I set a backslash at the beginning of my string (like in my example above), my alert pop up show "true" and I don't want that.
I code in Javascript
You can use String.raw to make sure that the backlash is not removed when testing your input:
var regex = /^\/add ([A-Za-z0-9]+)$/
var bool = regex.test(String.raw`\/add user1`);
alert(bool);
You can play with this code here: https://jsbin.com/ziqecux/25/edit?js

Why is this regex incorrect? [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 4 years ago.
I have the following regular expression:
\d{4}(-\d{2}){2}
Which is supposed to match dates that follow the YYYY-MM-DD format, so 1990-01-01 should successfuly match. However this fails when I try it in javascript.
var x = new RegExp('\d{4}(-\d{2}){2}')
x.test('1990-02-01') //why is this false?
Use the regular js regex syntax. Like this:
var x = /\d{4}(-\d{2}){2}/;
console.log(x.test('1990-02-01'));
if you want to keep the new RegExp part, you have to escape the string's backslashes:
var x = new RegExp('\\d{4}(-\\d{2}){2}');
console.log(x.test('1990-02-01'));

different results when using /.../ and RegEx with exec [duplicate]

This question already has an answer here:
Implicit and Explicit Regex creation yield different exec results
(1 answer)
Closed 7 years ago.
Why is this different?
var addressValue = "http://partners.webmasterplan.com/click.asp?ref=755891&site=8883&type=text&tnb=2&diurl=http://www.redcoon.de/B440080-Tefal-FV-9640_B%C3%BCgeleisen";
var reAffilinet = new RegExp("diurl=[(http|https):\/\/]*w*\.*([a-z]*)");
reAffilinet.exec(addressValue);
// ["diurl=http://www.redcoon.de/B440080-Tefal-FV-9640_B%C3%BCgeleisen", ""]
From this:
var addressValue = "http://partners.webmasterplan.com/click.asp?ref=755891&site=8883&type=text&tnb=2&diurl=http://www.redcoon.de/B440080-Tefal-FV-9640_B%C3%BCgeleisen";
var reAffilinet = /diurl=[(http|https):\/\/]*w*\.*([a-z]*)/;
reAffilinet.exec(addressValue);
// ["diurl=http://www.redcoon.de/B440080-Tefal-FV-9640_B%C3%BCgeleisen", ""]
As far as i understood this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions they should be the same...?
A convenient property of regex literals is you don't have to escape the \.
If you want to use the RegExp constructor, this escaping is necessary in order to define the string literal:
var reAffilinet = new RegExp("diurl=[(http|https):\\/\\/]*w*\\.*([a-z]*)");

Javascript regex in attribute [duplicate]

This question already has answers here:
Create RegExps on the fly using string variables
(6 answers)
Closed 8 years ago.
I need to use data attribute for regex just as
<div data-regex="REGEX-HERE">
and then get the value by javascript and put in a variable. and then do a test like
var regex = $(this).attr("data-regex");
regex.test(name)
when I tried to use "^[\x20-\x7E]+$" for testing english character is didn't work.
Note when I tried this
var regex = /^[\x20-\x7E]+$/;
It worked.
Thanks in advance
You can do this:
var regex = new RegExp("^[\x20-\x7E]+$",""); // Modifiers on the tend
So finally:
var regex = new RegExp($(this).data("regex"));
regex.test(name)

JS replacing all occurrences of string using variable [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 9 years ago.
I know that str.replace(/x/g, "y")replaces all x's in the string but I want to do this
function name(str,replaceWhat,replaceTo){
str.replace(/replaceWhat/g,replaceTo);
}
How can i use a variable in the first argument?
The RegExp constructor takes a string and creates a regular expression out of it.
function name(str,replaceWhat,replaceTo){
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}
If replaceWhat might contain characters that are special in regular expressions, you can do:
function name(str,replaceWhat,replaceTo){
replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}
See Is there a RegExp.escape function in Javascript?
The third parameter of flags below was removed from browsers a few years ago and this answer is no longer needed -- now replace works global without flags
Replace has an alternate form that takes 3 parameters and accepts a string:
function name(str,replaceWhat,replaceTo){
str.replace(replaceWhat,replaceTo,"g");
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Categories

Resources