So using jquery and I have a string of coordinates like so:
38.313072,-89.863845,38.312675,-89.863586,38.310405,-89.862091,38.310405,-89.862091,38.309913,-89.861976,38.309768,-89.861976,38.309768,-89.861976
I need them to look like this:
[38.313072, -89.863845] [38.312675, -89.863586] [38.310405, -89.862091] [38.310405,-89.862091] [38.309913, -89.861976] [38.309768, -89.861976] [38.309768, -89.861976] [38.30965, -89.861991]
So I need to figure out how to replace every other comma with a space and bracket sets of coordinates.
Ideas?
You can use regex.
([-\d.]+),([-\d.]+),?
Regex Explanation and Live Demo
[-\d.]: Character class, - will match literal - hyphen, \d will match a single digit, . will match . literally. When mentioned inside class sequence doesn't matter.+: Matches one or more occurrences of the previous matches(...): Capturing Group. The matches inside the braces are captured and returned in $1, $2, ...,?: To not match the every other commag: Global Match. To match all possible occurrences.jsFiddle Demo
var str = '38.313072,-89.863845,38.312675,-89.863586,38.310405,-89.862091,38.310405,-89.862091,38.309913,-89.861976,38.309768,-89.861976,38.309768,-89.861976';
var result = str.replace(/([-\d.]+),([-\d.]+),?/g, '[$1, $2] ').trim();
document.getElementById('output').innerHTML = JSON.stringify(result, 0, 2);
<pre id="output"></pre>
Use Regex ! It's perfect for this !
var str = "38.313072,-89.863845,38.312675,-89.863586,38.310405,-89.862091,38.310405,-89.862091,38.309913,-89.861976,38.309768,-89.861976,38.309768,-89.861976,38.30965, -89.861991";
var expected = "[38.313072, -89.863845] [38.312675, -89.863586] [38.310405, -89.862091] [38.310405,-89.862091] [38.309913, -89.861976] [38.309768, -89.861976] [38.309768, -89.861976] [38.30965, -89.861991]"
var computed = str.replace(/(([0-9\-. ]*)(,)([0-9\-. ]*)),?/g, '[$2 $3 $4] ');
document.write('computed<br>')
document.write(str.replace(/(([0-9\-. ]*)(,)([0-9\-. ]*)),?/g, '[$2 $3 $4] '))
document.write( "<hr>expected<br>" + expected )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With