Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove every other comma and surround with brackets

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?

like image 763
Dean Avatar asked Dec 08 '25 22:12

Dean


2 Answers

You can use regex.

([-\d.]+),([-\d.]+),?

Regex Explanation and Live Demo

  1. [-\d.]: Character class, - will match literal - hyphen, \d will match a single digit, . will match . literally. When mentioned inside class sequence doesn't matter.
  2. +: Matches one or more occurrences of the previous matches
  3. (...): Capturing Group. The matches inside the braces are captured and returned in $1, $2, ...
  4. ,?: To not match the every other comma
  5. g: 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>
like image 119
Tushar Avatar answered Dec 10 '25 12:12

Tushar


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  )
like image 33
Anonymous0day Avatar answered Dec 10 '25 12:12

Anonymous0day



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!