I have thousands of lines of Javascript code like this:
var myCoordinates = [
new google.maps.LatLng(11.11111,22.222222),
new google.maps.LatLng(33.33333,44.444444),
new google.maps.LatLng(55.55555,66.666666),
//thousands of lines
];
I need to format code above to this without whitespaces (a.k.a to string I could copy to my PHP code):
[["lat"=>11.11111,"lng"=>22.22222],["lat"=>33.33333,"lng"=>44.44444],["lat"=>55.55555,"lng"=>66.66666],/*etc*/];
What I've tried and failed:
document.getElementById('format-submit').onclick = function() {
var textareaValue = document.getElementById('format-textarea').value;
var findA = 'var myCoordinates = ';
var rA = new RegExp( findA, 'g' );
var resultA = textareaValue.replace( rA, '' );
//I get this error on this line:
//Uncaught SyntaxError: Invalid regular expression: /new google.maps.LatLng(/: Unterminated group
// |
// V
var findB = 'new google.maps.LatLng(';
var rB = new RegExp(findB, 'g');
var resultB = resultA.replace(rB, '["lat" => ');
var findC = '),';
var rC = new RegExp(findC, 'g');
var resultC = resultB.replace(rC, '],');
var findD = ')';
var rD = new RegExp(findD, 'g');
var finalResult = resultC.replace(rD, ']');
textareaValue = finalResult;
};
Speed or performance is not an issue, I just need to:
JS code to textareaQuestion:
How to replace part of string which has all kinds of letters, special characters etc in it?
(probable cause of error, right?)
I believe this is what you're looking for.
document.getElementById('format-submit').onclick = function() {
var textarea = document.getElementById('format-textarea');
textarea.value = textarea.value
.replace(/^[^\[]+/,'')
.replace(/^.*\(([\d.]+),([\d.]+)\)(,)?$/gm,'["lat" => $1, "lng" => $2]$3')
.replace(/\s+/g,'');
};
<textarea id="format-textarea" rows="7" cols="46">var myCoordinates = [
new google.maps.LatLng(11.11111,22.222222),
new google.maps.LatLng(33.33333,44.444444),
new google.maps.LatLng(55.55555,66.666666)
];</textarea><br>
<input type="button" id="format-submit" value="Format textarea">
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