Regex conversion from PHP to JavaScript [duplicate] - javascript

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 +.

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 +.

What is the regular expression to be used for the sequence of strings occured?

I have a structure of string, I need a regular expression that only picks up the numbers from the structure, and also the expression should report if the structure deviates from the mentioned rule (suppose if I missed any comma or full stop or braces etc)
The structure is - {'telugu':['69492','69493','69494'],'kannada':['72224']}
The regular expression I've tried is /\[(.*?)\]/g;
The above expression is working fine for picking only numbers from the given input, but it's not reporting for the missing of any comma, fullstop or braces etc.
var contentids = {'telugu':['69492','69493','69494'],'kannada':['72224']};
var pattern = /\[(.*?)\]/g;
while ((match = pattern.exec(contentids)) != null) {
var arrayContentids2 = new Array();
arrayContentids2 = match[1].split(",");
}
I am fetching only the numbers from the given input,but I need a validation of missing commas, fullstop, braces etc from the input.
To get all the numbers you can use a RegEx like this /\'(\d+)\'|\"(\d+)\"/g. The second part is only for numbers inside " instead of ', so you can remove this if you want.
To check the balance of braces i would use a simple counting loop and move through the input. I don't think that RegEx are the right tool for this job.
To search missing commas you could use the RegEx /([\'\"]\s*[\'\"])/g and /([\[\(\{]\d+)/g to find the tow errors in
{'telugu':['69492','69493','69494'],'kannada':[72224''72224']}
Hope this will help you

javascript regex to require at least one special character

I've seen plenty of regex examples that will not allow any special characters. I need one that requires at least one special character.
I'm looking at a C# regex
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
Can this be converted to use with javascript? Do I need to escape any of the characters?
Based an example I have built this so far:
var regex = "^[a-zA-Z0-9 ]*$";
//Must have one special character
if (regex.exec(resetPassword)) {
isValid = false;
$('#vsResetPassword').append('Password must contain at least 1 special character.');
}
Can someone please identify my error, or guide me down a more efficient path? The error I'm currently getting is that regex has no 'exec' method
Your problem is that "^[a-zA-Z0-9 ]*$" is a string, and you need a regex:
var regex = /^[a-zA-Z0-9 ]*$/; // one way
var regex = new RegExp("^[a-zA-Z0-9 ]*$"); // another way
[more information]
Other than that, your code looks fine.
In javascript, regexs are formatted like this:
/^[a-zA-Z0-9 ]*$/
Note that there are no quotation marks and instead you use forward slashes at the beginning and end.
In javascript, you can create a regular expression object two ways.
1) You can use the constructor method with the RegExp object (note the different spelling than what you were using):
var regexItem = new RegExp("^[a-zA-Z0-9 ]*$");
2) You can use the literal syntax built into the language:
var regexItem = /^[a-zA-Z0-9 ]*$/;
The advantage of the second is that you only have to escape a forward slash, you don't have to worry about quotes. The advantage of the first is that you can programmatically construct a string from various parts and then pass it to the RegExp constructor.
Further, the optional flags for the regular expression are passed like this in the two forms:
var regexItem = new RegExp("^[A-Z0-9 ]*$", "i");
var regexItem = /^[A-Z0-9 ]*$/i;
In javascript, it seems to be a more common convention to the user /regex/ method that is built into the parser unless you are dynamically constructing a string or the flags.

Javascript Regex on Intel Mac. Are patterns and subpattern replacement buggy?

I work with BBEdit on an Intel Mac with OS X Lion.
I want to turn str="a,b,c,d,e,f,g,h,i.j" into str=["a","b"]["c","d"]["e,"f"]["g","h"] using Javascript
I have tried this code:
var myArray = str.replace(/(\w+),(\w+)/g,"["$1","$2"]")
I have also tried with:
var re = new RegExp("(\w+),(\w+)", "g");
var myArray = str.replace(re,"["$1“,"$2“]" );
Both work with BBEdit's own search/replace tool and also with several online regex testers, but I can't get it to work within the script.
I have played around with the code for 2 days now and it seems the problem is interpreting the \w because
var myArray2 = str.replace(/\,/g,'\"\]\,\[\"')
works just fine to produce a"],["b"],["c"],["d"],["e"],["f"],["g"],["h"],["i"],["j
I have tried [a-zA-Z] instead of \w but this doesn't work either.
Has anyone experienced similar problems? Can anyone suggest a workaround?
I think I understand what you're trying to do, and the solution doesn't involve a regular expression. I'll try to explain why, first. Hear me out.
You're trying to solve your problem using .replace() and a regular expression, which implies that you're trying to convert the string 'str="a,b,c,d,e,f,g,h,i.j"' into the
string 'str=["a","b"]["c","d"]["e,"f"]["g","h"]'.
This is pretty easy, and you were almost there:
var original = 'str="a,b,c,d,e,f,g,h,i.j"';
var result = original.replace(/(\w+),(\w+)/g, '["$1","$2"]');
// result === 'str="["a","b"],["c","d"],["e","f"],["g","h"],i.j"';
Notice the mismatch in quotes around the replacement string. Alternatively, you could escape the quotes inside the string; "[\"$1\",\"$2\"]".
However, I doubt this is what you're trying to do. I think that instead, you're tyring to turn the string "a,b,c,d,e,f,g,h,i.j" into an array of arrays, which (in array literal notation) would be declared by: [["a","b"], ["c","d"], ["e,"f"], ["g","h"]].
This is not something you can do with a single regular expression. With a regular expression you can only can replace() a match, test() for a match, or return the match()es.
Try this, instead (also on JSFiddle):
var str = "a,b,c,d,e,f,g,h,i.j";
var parts = str.split(',');
var num_pairs = Math.floor(parts.length / 2);
var result = [];
for (var i=0; i < num_pairs; i+=1) {
result.push([parts[i*2], parts[(i*2)+1]]);
}
// result === [["a", "b"], ["c", "d"], ["e", "f"], ["g", "h"]]
Since the number of parts is uneven (i.j is the ninth element), you will have to decide whether it should be discarded (as in this example). If not, if change Math.floor to Math.round, the last array will be ["i.j", undefined].
By the way: regarding your original solution:
str.replace(/(\w+),(\w+)/g, "["$1","$2"]");
The reason this doesn't work has nothing to do with \w. It's just because it throws a SyntaxError. Try it, and look at your JavaScript error console.
This is because you didn't escape the "-qoutes inside the string, but you didn't concatenate either. I.e. you could have done this:
str.replace(/(\w+),(\w+)/g, "["+$1+","+$2+"]");
Notice the concatenation, using +. Now it's a valid string and won't throw a SyntaxError. It will, however, throw a TypeError, because the variables $1 and $2 are undefined. The key is to turn it into a full-on string:
str.replace(/(\w+),(\w+)/g, '["$1","$2"]');
// or
str.replace(/(\w+),(\w+)/g, "[\"$1\",\"$2\"]");
The replace() function will replace the $-parts in the string with matches values.

Split string in JavaScript using a regular expression

I'm trying to write a regex for use in javascript.
var script = "function onclick() {loadArea('areaog_og_group_og_consumedservice', '\x26roleOrd\x3d1');}";
var match = new RegExp("'[^']*(\\.[^']*)*'").exec(script);
I would like split to contain two elements:
match[0] == "'areaog_og_group_og_consumedservice'";
match[1] == "'\x26roleOrd\x3d1'";
This regex matches correctly when testing it at gskinner.com/RegExr/ but it does not work in my Javascript. This issue can be replicated by testing ir here http://www.regextester.com/.
I need the solution to work with Internet Explorer 6 and above.
Can any regex guru's help?
Judging by your regex, it looks like you're trying to match a single-quoted string that may contain escaped quotes. The correct form of that regex is:
'[^'\\]*(?:\\.[^'\\]*)*'
(If you don't need to allow for escaped quotes, /'[^']*'/ is all you need.) You also have to set the g flag if you want to get both strings. Here's the regex in its regex-literal form:
/'[^'\\]*(?:\\.[^'\\]*)*'/g
If you use the RegExp constructor instead of a regex literal, you have to double-escape the backslashes: once for the string literal and once for the regex. You also have to pass the flags (g, i, m) as a separate parameter:
var rgx = new RegExp("'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'", "g");
while (result = rgx.exec(script))
print(result[0]);
The regex you're looking for is .*?('[^']*')\s*,\s*('[^']*'). The catch here is that, as usual, match[0] is the entire matched text (this is very normal) so it's not particularly useful to you. match[1] and match[2] are the two matches you're looking for.
var script = "function onclick() {loadArea('areaog_og_group_og_consumedservice', '\x26roleOrd\x3d1');}";
var parameters = /.*?('[^']*')\s*,\s*('[^']*')/.exec(script);
alert("you've done: loadArea("+parameters[1]+", "+parameters[2]+");");
The only issue I have with this is that it's somewhat inflexible. You might want to spend a little time to match function calls with 2 or 3 parameters?
EDIT
In response to you're request, here is the regex to match 1,2,3,...,n parameters. If you notice, I used a non-capturing group (the (?: ) part) to find many instances of the comma followed by the second parameter.
/.*?('[^']*')(?:\s*,\s*('[^']*'))*/
Maybe this:
'([^']*)'\s*,\s*'([^']*)'

Categories