How to split this line with javascript?

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]; 

Conclusion:

 var split_1 = '37.961523'; var split_2 = '-79.40918'; 

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

+6
source share
4 answers

Using

 string.slice(1, -1).split(", "); 
+8
source

You can use regular expression to extract both numbers at the same time.

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

You would like to use regular expressions in this case:

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

EDIT Bug fixed in the comment below

+1
source

Here is another approach:

If () were [] , you would have valid JSON. So you can either change the code generating the coordinates to create [] instead of () , or replace them with:

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

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

 var coordinates = JSON.parse(str); 
0
source

Source: https://habr.com/ru/post/888677/


All Articles