Javascript: RegExp not working no matter what my expression is - javascript

Ok, I've been using RegExp a number of times but for some reason I cannot get it to work this time. I am trying to test for latitude (0 to +/- 90 degrees). No matter what expression I use, it always returns false. Here's my code:
var regexLatitude = new RegExp("^-?([1-8]?[0-9]\.{1}\d{1,6}$|90\.{1}0{1,6}$)");
var status = regexLatitude.test("89.5");
I also tried without quotes:
var status = regexLatitude.test(89.5);
Any idea?

Your \ characters are being parsed by the Javascript string literal.
You need to use a regex literal:
var regexLatitude = /^-?([1-8]?[0-9]\.{1}\d{1,6}$|90\.{1}0{1,6}$)/;

Related

Validate input value to allow only integer and decimal value using Js regex [duplicate]

I'm doing a small javascript method, which receive a list of point, and I've to read those points to create a Polygon in a google map.
I receive those point on the form:
(lat, long), (lat, long),(lat, long)
So I've done the following regex:
\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)
I've tested it with RegexPal and the exact data I receive:
(25.774252, -80.190262),(18.466465, -66.118292),(32.321384, -64.75737),(25.774252, -80.190262)
and it works, so why when I've this code in my javascript, I receive null in the result?
var polygons="(25.774252, -80.190262),(18.466465, -66.118292),(32.321384, -64.75737),(25.774252, -80.190262)";
var reg = new RegExp("/\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g");
var result = polygons.match(reg);
I've no javascript error when executing(with debug mode of google chrome). This code is hosted in a javascript function which is in a included JS file. This method is called in the OnLoad method.
I've searched a lot, but I can't find why this isn't working. Thank you very much!
Use a regex literal [MDN]:
var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;
You are making two errors when you use RegExp [MDN]:
The "delimiters" / are should not be part of the expression
If you define an expression as string, you have to escape the backslash, because it is the escape character in strings
Furthermore, modifiers are passed as second argument to the function.
So if you wanted to use RegExp (which you don't have to in this case), the equivalent would be:
var reg = new RegExp("\\(\\s*([0-9.-]+)\\s*,\\s([0-9.-]+)\\s*\\)", "g");
(and I think now you see why regex literals are more convenient)
I always find it helpful to copy and past a RegExp expression in the console and see its output. Taking your original expression, we get:
/(s*([0-9.-]+)s*,s([0-9.-]+)s*)/g
which means that the expressions tries to match /, s and g literally and the parens () are still treated as special characters.
Update: .match() returns an array:
["(25.774252, -80.190262)", "(18.466465, -66.118292)", ... ]
which does not seem to be very useful.
You have to use .exec() [MDN] to extract the numbers:
["(25.774252, -80.190262)", "25.774252", "-80.190262"]
This has to be called repeatedly until the whole strings was processed.
Example:
var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;
var result, points = [];
while((result = reg.exec(polygons)) !== null) {
points.push([+result[1], +result[2]]);
}
This creates an array of arrays and the unary plus (+) will convert the strings into numbers:
[
[25.774252, -80.190262],
[18.466465, -66.118292],
...
]
Of course if you want the values as strings and not as numbers, you can just omit the +.

Regex conversion from PHP to JavaScript [duplicate]

I'm doing a small javascript method, which receive a list of point, and I've to read those points to create a Polygon in a google map.
I receive those point on the form:
(lat, long), (lat, long),(lat, long)
So I've done the following regex:
\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)
I've tested it with RegexPal and the exact data I receive:
(25.774252, -80.190262),(18.466465, -66.118292),(32.321384, -64.75737),(25.774252, -80.190262)
and it works, so why when I've this code in my javascript, I receive null in the result?
var polygons="(25.774252, -80.190262),(18.466465, -66.118292),(32.321384, -64.75737),(25.774252, -80.190262)";
var reg = new RegExp("/\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g");
var result = polygons.match(reg);
I've no javascript error when executing(with debug mode of google chrome). This code is hosted in a javascript function which is in a included JS file. This method is called in the OnLoad method.
I've searched a lot, but I can't find why this isn't working. Thank you very much!
Use a regex literal [MDN]:
var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;
You are making two errors when you use RegExp [MDN]:
The "delimiters" / are should not be part of the expression
If you define an expression as string, you have to escape the backslash, because it is the escape character in strings
Furthermore, modifiers are passed as second argument to the function.
So if you wanted to use RegExp (which you don't have to in this case), the equivalent would be:
var reg = new RegExp("\\(\\s*([0-9.-]+)\\s*,\\s([0-9.-]+)\\s*\\)", "g");
(and I think now you see why regex literals are more convenient)
I always find it helpful to copy and past a RegExp expression in the console and see its output. Taking your original expression, we get:
/(s*([0-9.-]+)s*,s([0-9.-]+)s*)/g
which means that the expressions tries to match /, s and g literally and the parens () are still treated as special characters.
Update: .match() returns an array:
["(25.774252, -80.190262)", "(18.466465, -66.118292)", ... ]
which does not seem to be very useful.
You have to use .exec() [MDN] to extract the numbers:
["(25.774252, -80.190262)", "25.774252", "-80.190262"]
This has to be called repeatedly until the whole strings was processed.
Example:
var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;
var result, points = [];
while((result = reg.exec(polygons)) !== null) {
points.push([+result[1], +result[2]]);
}
This creates an array of arrays and the unary plus (+) will convert the strings into numbers:
[
[25.774252, -80.190262],
[18.466465, -66.118292],
...
]
Of course if you want the values as strings and not as numbers, you can just omit the +.

Validating Currency on Javascript using a regex not working

I need a regular expression for currency type.
Requirements :
1. First char can be a '$'. It can appear either 0 or 1 times.
2. Then a digit can appear multiple times.
3. Then a decimal point can appear either 0 or 1 time.
4. After this, a digit can appear 0 or more times.
I have written the following regular expression :
\$?\d+\.?\d*
I need to test this on JS . This is how i test this on JS;
var str = "$cng";
var patt = new RegExp('[\$?\d+\.?\d*]');
var res = patt.test(str);
console.log(res);
The above string $cng is returning true. I am not able to get it. Am i missing anything here. Can anyone please help. Thanks in advance.
You must need to escape all the backslashes one more times when passing it to the RegExp constructor which has double quotes as delimiter.
And also i suggest you to remove the square brackets around your pattern.
So change your pattern like below,
var patt = new RegExp("^\\$?\\d+\\.?\\d*$");
OR
var patt = new RegExp("^\\$?\\d+(?:\\.\\d+)?$");
Example:
> var str = "$123.12";
undefined
> var patt = new RegExp("^\\$?\\d+(?:\\.\\d+)?$");
undefined
> patt.test(str);
true
> var patt = new RegExp("^\\$?\\d+(?:\\.\\d+)?$");
undefined
> patt.test('$123.12$');
false
Replace RegExp('[\$?\d+\.?\d*]') with RegExp(/\$?\d+\.?\d*/) and it will work as expected.
Working Code Snippet:
var str = "$100.10";
var patt = new RegExp(/^\$?\d+\.?\d*$/);
var res = patt.test(str);
console.log(res);
EDIT:
You can also simply do: var res = /^\$?\d+\.?\d*$/.test(str);
Your regular expression should also match the beginning and end of the string, otherwise it will only test if the string contains a currency:
^\$?\d+\.?\d*$
You added brackets around the regular expression when you implemented it in Javascript, which changes the meaning entirely. The pattern will find a match if any of the characters within the brackets exist in the string, and as there is a $ in the string the result was true.
Also, when you have a regular expression in a string, you have to escape the backslashes:
var patt = new RegExp('^\\$?\\d+\\.?\\d*$');
You can also use a regular expression literal to create the object:
var patt = /^\$?\d+\.?\d*$/;
You might want to change the requirements so that the decimal point only is allowed if there are digits after it, so that for example $1. is not a valid value:
^\$?\d+(\.\d+)?$
[\$?\d+\.?\d*]==>[] is a character class.
Your regex will just match 1 character out of the all defined inside the character class.
Use
^\\$?\\d+\\.?\\d*$
or
/^\$?\d+\.?\d*$/
to be very safe.

Different behaviours when using regex in javascript

I'm using javascript and regex to scan a sentence for a particular word('schiz') then return the match along with 5 words in front of and behind my queried word.
However, I seem to be running into an odd situation, where the "new Regexp()" object doesn't behave the same way as just using the plain regex form.
In the following code, if I use:
reg = /([^\s]+\s){0,5}schiz([^\s]+\s){0,5}/g
then it returns as expected, but since I need the query word to be a variable, I need to use "new regexp()" to create my regex.
reg = RegExp("([^\s]+\s){0,5}"+query+"([^\s]+\s){0,5}","g");
Where query is "schiz", doesn't give the same result, can anyone explain why this is the case?
Here is the entire snippet:
var matchItem = "<p><strong>Indications</strong></p>
<p>- Used to treat "resistant schizophrenia" (resistant meaning pt has tried 2 other antipsychotics to little effect)</p>
<p>- Better for refractory schizophrenia than chlorpromazine</p>";
var query = "schiz";
var reg = RegExp("([^\s]+\s){0,5}"+query+"([^\s]+\s){0,5}","g");
//reg = /([^\s]+\s){0,5}schiz([^\s]+\s){0,5}/g
var ms = ("" + matchItem).match(reg);
if(ms!=null){
ms = ms.join("...");
}
return ms;
\ is a special character in a string literal, you have to escape it
"([^\\s]+\\s){0,5}"+query+"([^\\s]+\\s){0,5}"

RegExp.test not working?

I am trying to validate year using Regex.test in javascript, but no able to figure out why its returning false.
var regEx = new RegExp("^(19|20)[\d]{2,2}$");
regEx.test(inputValue) returns false for input value 1981, 2007
Thanks
As you're creating a RegExp object using a string expression, you need to double the backslashes so they escape properly. Also [\d]{2,2} can be simplified to \d\d:
var regEx = new RegExp("^(19|20)\\d\\d$");
Or better yet use a regex literal to avoid doubling backslashes:
var regEx = /^(19|20)\d\d$/;
Found the REAL issue:
Change your declaration to remove quotes:
var regEx = new RegExp(/^(19|20)[\d]{2,2}$/);
Do you mean
var inputValue = "1981, 2007";
If so, this will fail because the pattern is not matched due to the start string (^) and end string ($) characters.
If you want to capture both years, remove these characters from your pattern and do a global match (with /g)
var regEx = new RegExp(/(?:19|20)\d{2}/g);
var inputValue = "1981, 2007";
var matches = inputValue.match(regEx);
matches will be an array containing all matches.
I've noticed, for reasons I can't explain, sometimes you have to have two \\ in front of the d.
so try [\\d] and see if that helps.

Categories