javascript regex does not work properly with postal code - javascript

'^[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.

Related

javascript, declare associative array of regex expressions

How to declare associative array of regex?
This is not working
var Validators = {
url : /^http(s?)://((\w+\.)?\w+\.\w+|((2[0-5]{2}|1[0-9]{2}|[0-9]{1,2})\.){3}(2[0-5]{2}|1[0-9]{2}|[0-9]{1,2}))(/)?$/gm
};
EDITED: Now working!
This will be valid in JS (like # operator in C#)
url : `/^http(s?)://((\w+\.)?\w+\.\w+|((2[0-5]{2}|1[0-9]{2}|[0-9]{1,2})\.){3}(2[0-5]{2}|1[0-9]{2}|[0-9]{1,2}))(/)?$/gm`
However, will still not work due to double escape, one in JS and other in Regex. If expression is small, perhaps naked eye can manually escape for both JS and Regex. My brain just can't :)
In order to use strings as tested on regex101.com for example, all required strings should be declared as 'row' like this:
var exp = String.raw`^(http(s?):\/\/)?(((www\.)?[a-zA-Z0-9\.\-\_]+(\.[a-zA-Z]{2,3})+)|(\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b))(\/[a-zA-Z0-9\_\-\s\.\/\?\%\#\&\=]*)?$`;
var strings = [
String.raw`http://www.goo gle.com`,
String.raw`http://www.google.com`,
];
Wrap it with new RegExp() and escape slashes
var Validators = {
url : new RegExp( /^http(s?):\/\/((\w+\.)?\w+\.\w+|((2[0-5]{2}|1[0-9]{2}|[0-9]{1,2})\.){3}(2[0-5]{2}|1[0-9]{2}|[0-9]{1,2}))(\/)?$/gm )
};
Your regex has forward slashes in it. This symbol needs to be escaped because it is supposed to indicate the start and end of the expression. Try \/.

Regex to detect a string that contains a URL or file extension

I'm trying to create a small script that detects whether the string input is either:
1) a URL (which will hold a filename): 'http://ajax.googleapis.com/html5shiv.js'
2) just a filename: 'html5shiv.js'
So far I've found this but I think it just checks the URL and file extension. Is there an easy way to make it so it uses an 'or' check? I'm not very experienced with RegExp.
var myRegExp = /[^\\]*\.(\w+)$/i;
Thank you in advance.
How bout this regex?
(\.js)$
it checks the end of the line if it has a .js on it.
$ denotes end of line.
tested here.
Basically, to use 'OR' in regex, simply use the 'pipe' delimiter.
(aaa|bbb)
will match
aaa
or
bbb
For regex to match a url, I'd suggest the following:
\w+://[\w\._~:/?#\[\]#!$&'()*+,;=%]*
This is based on the allowed character set for a url.
For the file, what's your definition of a filename?
If you want to search for strings, that match "(at least) one to many non-fullstop characters, followed by a fullstop, followed by (at least) one to many non-fullstop characters", I'd suggest the following regex:
[^\.]+\.[^\.]+
And altogether:
(\w+://[\w\._~:/?#\[\]#!$&'()*+,;=%]*|[^\.]+\.[^\.]+)
Here's an example of working (in javascript): jsfiddle
You can test it out regex online here: http://gskinner.com/RegExr/
If it is for the purpose of flow control you can do the following:
var test = "http://ajax.googleapis.com/html5shiv.js";
// to recognize http & https
var regex = /^https?:\/\/.*/i;
var result = regex.exec(test);
if (result == null){
// no URL found code
} else {
// URL found code
}
For the purpose of capturing the file name you could use:
var test = "http://ajax.googleapis.com/html5shiv.js";
var regex = /(\w+\.\w+)$/i;
var filename = regex.exec(test);
Yes, you can use the alternation operator |. Be careful, though, because its priority is very low. Lower than sequencing. You will need to write things like /(cat)|(dog)/.
It's very hard to understand what you exactly want with so few use/test cases, but
(http://[a-zA-Z0-9\./]+)|([a-zA-Z0-9\.]+)
should give you a starting point.
If it's a URL, strip it down to the last part and treat it the same way as "just a filename".
function isFile(fileOrUrl) {
// This will return everything after the last '/'; if there's
// no forward slash in the string, the unmodified string is used
var filename = fileOrUrl.split('/').pop();
return (/.+\..+/).test(filename);
}
Try this:
var ajx = 'http://ajax.googleapis.com/html5shiv.js';
function isURL(str){
return /((\/\w+)|(^\w+))\.\w{2,}$/.test(str);
}
console.log(isURL(ajx));
Have a look at this (requires no regex at all):
var filename = string.indexOf('/') == -1
? string
: string.split('/').slice(-1)[0];
Here is the program!
<script>
var url="Home/this/example/file.js";
var condition=0;
var result="";
for(var i=url.length; i>0 && condition<2 ;i--)
{
if(url[i]!="/" && url[i]!="."){result= (condition==1)? (url[i]+result):(result);}
else{condition++;}
}
document.write(result);
</script>

jquery .replace(/./g, "") do not work for me but others

I found this snippet somewhere and it works like a charm:
var n = parseInt(e.find("span.favNum").text().replace(/./g, "")) + 1;
If I do it in a similar way it doesn't work anymore.
I do the following:
<div id ="test">6.987</div>
var test = $("#test");
var r = test.text().replace(/./g, "");
console.log("wrong ", r);
I know that I can replace it also like this:
var r = test.text().replace(".", "");
This works.
I would like to understand why the "stolen" snippet is working.
Any idea?
http://jsfiddle.net/nJZMf/3/
The original script is found here: http://wp-svbtle.themeskult.com/
You will find the snippet by viewing the source of index.html and searching for .replace.
You need to escape the "."
test.text().replace(/\./g, "");
The reason that the code in the page you linked to works, where yours doesn't, is that it's not the same regular expression. Here's what I found in that page (and similar code in several places)
r = n.text().replace( /,/g, "" )
where r is a jQuery object.
Note that the regular expression has a , inside the //, not a . like the code you had trouble with.
Comma is not a special character in regular expressions, so it needs no special treatment. Period has a special meaning. As the other answers pointed out, it matches all characters, and you need to prefix it with \ if you want to match . only.
Also note that .replace() is not jQuery code, it's JavaScript.
jQuery's .text() method returns a JavaScript String value. So anything you do with that string - such as the .replace() call - is actually a JavaScript String method.
The distinction is important when you want to research a problem: a search for "javascript string replace" will get you better information than "jquery replace".
It has to be var r = test.text().replace(/\./g, ""); instead of var r = test.text().replace(/./g, ""); because you need to escape the . in order for it to be replaced.
http://jsfiddle.net/mrk1989/nJZMf/4/
Solution because I add \ in var r = test.text().replace(/\./g, "");
The problem was that you did not escape dot.
But keep in mind that:
.replace(".", "");
.replace(/\./g, "");
are two different things.
For example: https://jsfiddle.net/rmhpkz9n/1/

Jquery check for alphanumeric charactres

In the below code Using jquery how to check for only alaphanumeric charaters.Even space and none of the special symbols should be allowed.I do want o use a external plugin
var a='a hjdshj%^& ff234 ./.';
if(var a has special characters)
{
alert('has special characters');
}
EDIT : Even single and double quotes should not be allowed
There is no need of any plugin to check this
you can make use of Regular exprssion to do it easily..
try this
var str='a hjdshj%^& ff234 ./.';
var re = new RegExp(/\$|\/|\^|-/\s,"g");
specialchars = str.match(re);
alert(specialchars.length);

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