I'm validating date (Format is YYYY/MM/DD) using regular expression ng-pattern. When i use below code in UI, it's working fine.
<input type="text" class="k-fill" ng-pattern="/((^[1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))\/([0]{1}[1-9]{1}|[1]{1}[0-2]{1})\/([0]{1}[1-9]{1}|[1,2]{1}\d{1}|[3]{1}[0,1]{1})$/" ng-model="Request.ExpDate" id="ExceptedDate" name="ExceptedDate" ng-readonly="true" required />
But i want to validate the pattern inside of a function for pop-up a validation message. For achieving it I used below code inside one of my js file.
var str = Request.ExpDate;
var x = '/((^[1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))\/([0]{1}[1-9]{1}|[1]{1}[0-2]{1})\/([0]{1}[1-9]{1}|[1,2]{1}\d{1}|[3]{1}[0,1]{1})$/';
var patt = new RegExp(x);
var res = patt.test(str);
if res return false, I can show a message. But the problem is, it is returning false for every dates which are even in the right format.
May I know the reason for why the regexp is working fine with ng-pattern and why it is not working properly inside JS function?
Your regex returns false all the time because you included regex delimiters in the pattern that you initialize with a constructor notation (new RegExp(var)).
You do not have to use a constructor and can initialize RegExp using a regular literal in the form of /.../:
var str = Request.ExpDate;
var patt = /((^[1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))\/([0]{1}[1-9]{1}|[1]{1}[0-2]{1})\/([0]{1}[1-9]{1}|[1,2]{1}\d{1}|[3]{1}[0,1]{1})$/;
var res = patt.test(str);
However, it seems your regex has some issues in it, here is a fixed version:
/^((199\d)|([2-9]\d{3}))\/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])$/
I removed {1} limiting quantifier since it is redundant, and removed , from inside the character classes [1,2] and [0,1] since the comma was treated as a literal, and could mess up the results. We can also further enhance by removing unnecessary groups or turning them to non-capturing, but those are already cosmetic changes.
See sample:
var str = "2992/10/31";
var patt = /^((199\d)|([2-9]\d{3}))\/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])$/;
var res = patt.test(str);
document.write(res);
Note that you could also make use of Date.Parse to validate the date more precisely.
Related
So basically, I have a regular expression which is
var regex1 = /10661\" class=\"fauxBlockLink-linkRow u-concealed\">([\s\S]*?)<\/a>/;
var result=text.match(regex1);
user_activity = result[1].replace(/\s/g, "")
console.log(user_activity);
What I'm trying to do is this
var number = 1234;
var regex1 = /${number}\" class=\"fauxBlockLink-linkRow u-concealed\">([\s\S]*?)<\/a>/;
but it is not working, and when I tried with RegExp, I kept getting errors.
You can use RegExp to create regexp from a string and use variables in that string.
var number = 1234;
var regex1 = new RegExp(`${number}aa`);
console.log("1234aa".match(regex1));
You can build the regex string with templates and/or string addition and then pass it to the RegExp constructor. One key in doing that is to get the escaping correct as you need an extra level of escaping for backslashes because the interpretation of the string takes one level of backslash, but you need one to survive as it gets to the RegExp contructor. Here's a working example:
function match(number, str) {
let r = new RegExp(`${number}" class="fauxBlockLink-linkRow u-concealed">([\\s\\S]*?)<\\/a>`);
return str.match(r);
}
const exampleHTML = 'Some link text';
console.log(match(1234, exampleHTML));
Note, using regex to match HTML like this becomes very order-sensitive (whereas the HTML itself isn't order-sensitive). And, your regex requires exactly one space between classes which HTML doesn't. If the class names were in a slightly different order or spacing different in the <a> tag, then it would not match. Depending upon what you're really trying to do, there may be better ways to parse and use the HTML that isn't order-sensitive.
I solved it with the method of Adem,
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
var number = 1234;
var firstPart = `<a href="/forum/search/member?user_id=${number}" class="fauxBlockLink-linkRow u-concealed">`
var regexpString = escapeRegExp(firstPart) + '([\\s\\S]*?)' + escapeRegExp('</a>');
console.log(regexpString)
var sample = ` `
var regex1 = new RegExp(regexpString);
console.log(sample.match(regex1));
in the first place the issue was actually the way I was reading the file, the data I was applying the match on, was undefined.
I want to make the first character of every word in a string to uppercase.
i am referring to this article Replacement Text Case Conversion.
when i am running the regular expression ([a-zA-Z])([a-zA-Z](\s)) with the replacement text as \u$1\l$2 in my editor (sublime text) it works fine.
However, when i am trying to do the same in javascript using replace method as below, its giving syntax errors and hence fails.
var regex = /([a-zA-Z])([a-zA-Z]*(\s)*)/gi;
var rep = "\\u$1\\l$2"; // here it is giving error
var result = input.replace(regex,rep);
How to resolve this?
I know this problem can be solved using charAt() and toUppercase() method. but I want to do it using regex with replace. :)
JS regex engine does not support lower- and uppercasing operators \u and \l in the replacement patterns. Use a callback inside String#replace:
var input = "aZ";
var regex = /([a-zA-Z])([a-zA-Z]*(\s)*)/gi;
var result = input.replace(regex, function($0,$1,$2,$3) {
return $1.toUpperCase() + $2.toLowerCase();
});
console.log(result);
Note that you can reduce your pattern to /([a-z])([a-z]*\s*)/gi.
I have the following code that checks a URL if it contains a certain pattern:
var url = "https://www.google.co.uk/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=regex%20javascript";
var patt = new RegExp('https?:\/\/[^/]+\.google\.[a-z.]+\/((search[?#])|(webhp[?#])|([?#])).*q=');
var check = patt.test(url);
alert(check);
The above regex won't work without using new RegExp(). How do I use the same regex without creating the regex object. For example, something like this (which doesn't seem to work):
var url = "https://www.google.co.uk/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=regex%20javascript";
var check = ('https?:\/\/[^/]+\.google\.[a-z.]+\/((search[?#])|(webhp[?#])|([?#])).*q=').test(url);
alert(check);
Do you mean a regex literal like so
var check = /https?:\/\/[^/]+\.google\.[a-z.]+\/((search[?#])|(webhp[?#])|([?#])).*q=/.test(url)
this is however merely syntactic sugar and does not free you of creating actual RegEx objects
I'm doing kind of a reverse templating thing, I have a string, and I know the template used to generate it, I want to get the variable value.
For example:
URL: http://c.tile.osm.org/24/7881145/7385476.png
Template: http://{s}.tile.osm.org/{z}/{x}/{y}.png
I would like to get the zoom level ({z}) from the tile's URL, in this case 24. This exact Template url will not always be used (it varies based on what basemap is used, etc.), but I'll always be looking for the {z} value.
It looks like blint may have beat me to it, but essentially what you want to do is generate a regular expression from your template and execute it:
function zFromTemplate(str, template) {
var sr = template.replace("?", "\\?")
.replace(/\{[^z]\}/g, ".*?")
.replace(/\{z\}/g, "(.+)");
var rex = new RegExp(sr),
parts = rex.exec(str);
if(parts) {
return parts[1];
}
return null;
}
And here's a codepen demonstrating it's use. If nothing else it's a little more succinct than the originally accepted answer.
You can capture values using a regex. This thread is similar to your case, and here would be your solution:
var myString = "http://c.tile.osm.org/24/7881145/7385476.png";
var myRegexp = /http:\/\/[A-z]\.tile\.osm\.org\/([0-9]+)\/([0-9]+)\/([0-9]+)\.png/;
var match = myRegexp.exec(myString);
alert(match[1]); // 24
And here's the fiddle: http://jsfiddle.net/2sx4t/
EDIT:
Following to your comment, here's the most flexible code I could quickly provide you: http://jsfiddle.net/2sx4t/4/
var myString = "http://c.tile.osm.org/24/7881145/7385476.png";
var myTemplate = "http://{s}.tile.osm.org/{z}/{y}/{x}.png";
var myString2 = "//tiles.arcgis.com/tiles/c/arcgis/rest/services/TimeZones/MapServer/tile/223774/24/2636";
var myTemplate2 = "//tiles.arcgis.com/tiles/{s}/arcgis/rest/services/TimeZones/MapServer/tile/{x}/{z}/{y}";
var z = extractToken(myTemplate, myString, '{z}');
alert(z); // 24
var z2 = extractToken(myTemplate, myString, '{z}');
alert(z2); // 24
The tricks in this code is the combination of the use of template.indexOf(m) to be able to find the order of your tokens and String.replace() to generate the appropriate RegExp.
Note that I shuffled the order of the tokens in myTemplate2and that it sill works.
Don't expect magic from RegExp, magic is in our brains ;-)
Bonus with map return, independantly of other tokens: http://jsfiddle.net/2sx4t/8/
Well, if you're sure that the {z} parameter is the only 1 or 2 digits element in your URL, you can try with regexp:
var myRegexp = /.*\/([0-9]{1,2})\/.*/;
This would match the last occurrence of any one or two digits enclosed in two slashes (/1/, /24/, ...)
'^[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.