new RegExp. test - javascript

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_.-]+)$/;

Related

regular expression to extract two items from a long string

There are some strings having the following type of format,
{abc=1234457, cde=3, label=3352-4e9a-9022-1067ca63} <chve> abc? 123.456.789, http=appl.com
I would like to extract 1234457 and 3352-4e9a-9022-1067ca63, which correspond to abc and label respectively.
This is the javascript I have been trying to use, but it does not work. I think the regular expression part is wrong.
var headerPattern = new RegExp("\{abc=([\d]*),,label=(.*)(.*)");
if (headerPattern.test(row)) {
abc = headerPattern.exec(row)[0];
label = headerPattern.exec(row)[1];
}
Try: abc=(\d*).*?label=([^}]*)
Explanation
abc= literal match
(\d*) catch some numbers
.*? Lazy match
label= literal match
([^}]*) catch all the things that aren't the closing brace
Here is what I came up with:
\{abc=(\d+).*label=(.+)\}.*
Your have two problems in \{abc=([\d]*),,label=(.*)(.*):
Using abc=([\d]*),,, you are looking for abc=([\d]*) followed by the literal ,,. You should use .* instead. Since .* is nongreedy be default, it will not match past the label.
By using label=(.*)(.*), the first .* captures all the remaining text. You want to only catch text until the edge of the braces, so use (.*)}.*.
Disclaimer: Made with a Java-based regex tester. If anything in JavaScript regexes would invalidate this, feel free to comment.
You can do it the following way:
var row = '{abc=1234457, cde=3, label=3352-4e9a-9022-1067ca63} <chve> abc? 123.456.789, http=appl.com';
var headerPatternResult = /{abc=([0-9]+),.*?label=([a-z0-9\-]+)}/.exec(row);
if (headerPatternResult !== null) {
var abc = headerPatternResult[1];
var label = headerPatternResult[2];
console.log('abc: ' + abc);
console.log('label: ' + label);
}

Using regex to split double hyphen but not single hyphen

I have an html element id that looks like this:
dp__1-2--1-3
I'm trying to use the JavaScript split() function to lop off and return the final '1-3'
My regex skills are poor but a bit of searching around got me to this point:
var myId = "dp__1-2--1-3";
var myIdPostFix = myId.split(/[\-\-]+/).pop();
Unfortunately that returns me only the '3'.
So my question is how do I split double hyphens but NOT single hyphens?
It's the brackets in the regular expression that keeps it from working. A set will match one of any of the characers in it, so [\-\-] is the same as [\-], i.e. matching a single hyphen.
Just remove the brackets:
var myIdPostFix = myId.split(/--/).pop();
or just use the string '--' instead of a regular expression:
var myIdPostFix = myId.split('--').pop();
split accepts a regular expression or a string as the first argument.
You were very close. You can achieve what you want with:
var myIdPostFix = myId.split("--").pop();

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.

Trimming String in Javascript

I have string like var a=""abcd""efgh"".How do I print the output as abcd""efgh by removing first and last double quote of a string I used a.replace(/["]/g,'') but it is removing all the double quotes of a string.How do i get the output as abcd""efgh.Suggest me an idea.
You can use
var a='"abcd""efgh"';
a.replace(/^"+|"+$/g, '');
From the comments here is the explanation
Explanation
There are 2 parts ^"+ and "+$ separated by | which is the regex equivalent of the or
^ is for starts-with and "+ is for one or more "
Similarly $ is for ends-with
The //g is for global replacement otherwise the only the first occurrence will be replaced
Try use this
var a='"abcd""efgh"';
a.replace(/^"|"$/g, '');

java script Regular Expressions patterns problem

My problem start with like-
var str='0|31|2|03|.....|4|2007'
str=str.replace(/[^|]\d*[^|]/,'5');
so the output becomes like:"0|5|2|03|....|4|2007" so it replaces 31->5
But this doesn't work for replacing other segments when i change code like this:
str=str.replace(/[^|]{2}\d*[^|]/,'6');
doesn't change 2->6.
What actually i am missing here.Any help?
I think a regular expression is a bad solution for that problem. I'd rather do something like this:
var str = '0|31|2|03|4|2007';
var segments = str.split("|");
segments[1] = "35";
segments[2] = "123";
Can't think of a good way to solve this with a regexp.
Here is a specific regex solution which replaces the number following the first | pipe symbol with the number 5:
var re = /^((?:\d+\|){1})\d+/;
return text.replace(re, '$15');
If you want to replace the digits following the third |, simply change the {1} portion of the regex to {3}
Here is a generalized function that will replace any given number slot (zero-based index), with a specified new number:
function replaceNthNumber(text, n, newnum) {
var re = new RegExp("^((?:\\d+\\|){"+ n +'})\\d+');
return text.replace(re, '$1'+ newnum);
}
Firstly, you don't have to escape | in the character set, because it doesn't have any special meaning in character sets.
Secondly, you don't put quantifiers in character sets.
And finally, to create a global matching expression, you have to use the g flag.
[^\|] means anything but a '|', so in your case it only matches a digit. So it will only match anything with 2 or more digits.
Second you should put the {2} outside of the []-brackets
I'm not sure what you want to achieve here.

Categories

Resources