6

Javascript:

var string = '(37.961523, -79.40918)';

//remove brackets: replace or regex? + remove whitespaces

array = string.split(',');

var split_1 = array[0];

var split_2 = array[1];

Output:

var split_1 = '37.961523';

var split_2 = '-79.40918';

Should I just use string.replace('(', '').replace(')', '').replace(/\s/g, ''); or RegEx?

2
  • 2
    if this format is NOT going to change, regex is definitely an overkill. Commented May 20, 2011 at 21:39
  • 2
    what is the question? what you have works Commented May 20, 2011 at 21:39

4 Answers 4

8

Use

string.slice(1, -1).split(", ");
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a regex to extract both numbers at once.

var string = '(37.961523, -79.40918)';
var matches = string.match(/-?\d*\.\d*/g);

Comments

1

You would probably like to use regular expressions in a case like this:

str.match(/-?\d+(\.\d+)?/g); // [ '37.961523', '-79.40918' ]

EDIT Fixed to address issue pointed out in comment below

1 Comment

Your regex would fail for any integer number less than 10 and greater than -10.
0

Here is another approach:

If the () were [] you would have valid JSON. So what you could do is either change the code that is generating the coordinates to produce [] instead of (), or replace them with:

str = str.replace('(', '[').replace(')', ']')

Then you can use JSON.parse (also available as external library) to create an array containing these coordinates, already parsed as numbers:

var coordinates = JSON.parse(str);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.