Question

How to do this in a more "elegant way"?

var str = obj.property.toString(); //str value = (55.930385, -3.118425)
var remesp = str.replace(" ","");
var rempar1 = remesp.replace("(","");
var rempar2 = rempar1.replace(")",""); //rempar2 value = "55.930385,-3.118425"
Was it helpful?

Solution

Try using a regular expression character class (aka "character set") [...]:

var str = "(55.930385, -3.118425)";

str.replace(/[ ()]/g, ''); // => "55.930385,-3.118425"

In the example above, the regex /[ ()]/ matches any space or open/close parenthesis character.

OTHER TIPS

The more elegant way would be using proper regex syntax in replace().

Switch ( and ) with [ and ] and use JSON.parse() to get the numbers into your new array.

var str = "(55.930385, -3.118425)".replace("(","[").replace(")","]"); 
var coords = JSON.parse(str);

If you need to support older browsers, you will need to use a JSON.parse shim or another solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top