Reputation:
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?
Upvotes: 6
Views: 169
Reputation: 816452
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);
Upvotes: 0
Reputation: 28429
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
Upvotes: 1
Reputation: 227260
You can use a regex to extract both numbers at once.
var string = '(37.961523, -79.40918)';
var matches = string.match(/-?\d*\.\d*/g);
Upvotes: 1