Why this javascript regex doesn’t work?

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

Leave a Comment