Why this JavaScript RegExp results in dual answer? - javascript

Look at this simple HTML input tag:
<input type='text' id='phoneNumber' name='phoneNumber' class='inputBig textLeft'
data-validation='required regex'
data-validation-regex-pattern='^\\+\\d{2}\\.\\d{10}$'
value='+98.2188665544' />
<p id='log'></p>
Now imagine that we want to validate this field, using this function:
var log = $('#log');
function validateRegex(field) {
var pattern = field.attr('data-validation-regex-pattern');
log.append(pattern + '<br />');
if (pattern && pattern != '') {
var isValid = new RegExp(pattern).test(field.val().trim());
if (!isValid) {
log.append('not valid<br />');
}
else {
log.text('valid<br />');
}
}
}
validateRegex($('#phoneNumber'));
var isValid = new RegExp('^\\+\\d{2}\\.\\d{10}$').test($('#phoneNumber').val());
log.append(isValid.toString());
Now, if you look at the log, you see that this line returns false:
var isValid = new RegExp(pattern).test(field.val().trim());
However, this line of code returns true:
new RegExp('^\\+\\d{2}\\.\\d{10}$').test($('#phoneNumber').val().trim());
In other words, when the pattern of the RegExp object is passed to it as a string variable, it doesn't work. But when you pass a string literal, it works.
Why? What's wrong here?
To see it in action, look at this fiddle.

Escaping backslashes applies only to JavaScript, it isn't necessary for HTML. Therefore, the following attribute string:
data-validation-regex-pattern='^\+\d{2}\.\d{10}$'
Will work just fine:
Updated fiddle: http://jsfiddle.net/AndyE/GRL2m/6/

\\ is the method to write \ in a JavaScript String. The HTML data-attribute, written in JS would be \\\\, instead of \\.
Eg: <a data-x="\\">(HTML) is equivalent to '<a data-x="\\\\">' (JS).
To get your code work, replace double slashes (\\) in your HTML by a single slash.Fiddle: http://jsfiddle.net/GRL2m/5/
Extra information:
In HTML, HTML entities (eg ") are used to display special characters.
In JavaScript, escapes (eg \n, \x20, \u0009, ..) are used to display special characters.
In a RegExp, special RE characters have to be escaped by a slash (/\./). When the RegExp is constructed using a string, the slash has to be escaped, so that the slash also appear at the RegExp. "\." equals '.', while "\\." equals '\.'.

Related

Regex to match forward or backward slash

I have a string like this :
whatever/aaazzzzz
and sometimes a string like that :
whatever\bbbbzzzzz
I would like to split the string when I match / or \
The regex I tried seems to work
https://regex101.com/r/gP5gL0/1
When I use it in the fiddle, it works with / but not with \
Any ideas?
The issue here is not the regex itself, but the unavoidable fact that JavaScript doesn't implicitly support string literals (i.e. ones where backslashes are interpreted as printed as opposed to denoting an escape sequence. Much more can read here).
Strings derived from any source other than source code are interpreted as literal by default, as demonstrated in this fiddle.
<script>
function splitTheString()
{
//test = escape("whatever\aaaaaa");
var test = document.getElementById("strToSplit").value;
a = test.split(/(\\|\/)/)[0];
alert(a);
}
</script>
<form>
Split this string:<br>
<input type="text" id="strToSplit">
Split the string
</form>
Use this
var arr = str.split(/[\\|\/]/);
var str = 'whatever\\bbbbzzzzz';
alert(str.split(/[\\|\/]/))

HTML special characters does not replaced by Javascript

I'm trying to decode some specail characters in my string, before input it in HTML. But, for some reason, it didn't work.
For ex:
My input string is "ampere 13th\'."
In JS I'm replacing every special character with this function:
htmlEntities: function(str) {
return str.replace(/\\/g, "\").replace("'", "'").replace(".", ".").replace("%", "%").replace("\"",""");
},
But, when put it to HTML, it still looks like :
"ampere 13th\'."
I want to show my data with replaced special characters.
What I'm doing wrong?
There is a single backslash in your string which is not being recognized as '\' but instead its an escape sequence. Other characters are being replace perfectly. I have written the following function which alerts the output string accordingly.
function test() {
var str = "ampere 13th\'.";
alert(str.replace(/\\/g, "&#92").replace("'", "'").replace(".", ".").replace("%", "%").replace("\"", """));
}
And it alerts me
ampere 13th'.
which is correct except replacing the '\' character. if you want to replace the '\' you can further search on how to replace a backslash character in java script.
if I have my input string like this
var str = "ampere 13th\\'.";
with two backslashes then the replacement occurs perfectly and my function alerts me
ampere 13th&#92'.

Regex checking lat/lon in JavaScript

I'm such a newb in regex, but still...
I based my test on this post.
I have this simple regex :
^-?([1]?[1-7][1-9]|[1]?[1-8][0]|[1-9]?[0-9])\.{1}\d{1,6}
In Debuggex, if I test it with 88.5 for example, it matches.
In my JS file, I have :
var lonRegex = new RegExp("^-?([1-8]?[1-9]|[1-9]0)\.{1}\d{1,6}");
var check = lonRegex.test(88.5); // hardcoded for demo
console.log(check) // output false
I can't guess why it's always returning me false, whatever the value is a number or a string like "88.5".
You will need to escape some characters when creating a RegExp object from a string. From MDN:
When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.
In your case, this will work (note the double \ for \d and .):
var lonRegex = new RegExp("^-?([1-8]?[1-9]|[1-9]0)\\.{1}\\d{1,6}");
var check = lonRegex.test(88.5); // hardcoded for demo
console.log(check) // output true

javascript regex does not work properly with postal code

'^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]{1}\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}[ -]*\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}\d{1}$'
the above regular expression accepts inputs like T3K2H3 or T3K-2H3 from .net form but when i run the validation through the javascript; it does not work.
var rxPostalCode = new RegExp('^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]{1}\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}[ -]*\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}\d{1}$');
var postalCode = 't3k2h3';
var matchesPostalCode = rxPostalCode.exec(postalCode);
if (matchesPostalCode == null || postalCode != matchesPostalCode[0]) {
$scope.AccountInfoForm.PostalCode.$setValidity("pattern", false);
$scope.showLoading = false;
return false;
}
I believe that in javascript, you have to do // instead of ''
as follows:
/^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]{1}\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}[ -]*\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}\d{1}$/
You might want to check the following link:
Validate email address in JavaScript?
You have two syntaxes to define a regexp object:
var rxPostalCode = /^[abceghj-np-tvxy]\d[abceghj-np-tv-z][ -]?\d[abceghj-np-tv-z]\d$/i;
or
var rxPostalCode = new RegExp('^[abceghj-np-tvxy]\\d[abceghj-np-tv-z][ -]?\\d[abceghj-np-tv-z]\\d$', 'i');
Note that with the second syntax you need to use double backslashes.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
"Do not forget to escape \ itself while using the RegExp("pattern") notation because \ is also an escape character in strings."
var rxPostalCode = new RegExp('^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]{1}\\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}[ -]*\\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}\\d{1}$');
That should work, I tested it in Chrome's console.
Try the following pattern:
^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]\d
[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz][ -]*\d
[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]\d
Remove the $ at the end and see if that solves your problem.
I also simplified things a bit, the \d{1} is the same as \d
I would also change the [ -]* to [ -]? unless you want to allow multiple spaces or dashes
I suspect what is happening is that the $ expect the end of the line or string, and JavaScript may not store the VAR properly. See if remove the $ solves it, or possibly keeping the $ and trim() the string.

new RegExp. test

I have posted a problem in the above link - regExpression.test.
Based on that I have done like bellow that also produces an error.
var regExpression=new RegExp("^([a-zA-Z0-9_\-\.]+)$");
alert (regExpression.test("11aa"));
You need to escape your \ since you're declaring it with a string, like this:
var regExpression=new RegExp("^([a-zA-Z0-9_\\-\\.]+)$");
^ ^ add these
You can test it here.
You can also use the literal RegExp syntax /…/:
var regExpression = /^([a-zA-Z0-9_\-\.]+)$/;
By the way: The . does not need to be escaped in character classes anyway. And if you put the range operator at the begin or the end of the character class or immediately after a character range, it doesn’t need to be escaped either:
var regExpression = /^([a-zA-Z0-9_.-]+)$/;

Categories

Resources