Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reconstruct array

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:

  1. Copy first JS code to textarea
  2. Format it when button is pressed
  3. Replace textarea value with formatted code
  4. Copy it
  5. Paste it to my code

Question:

How to replace part of string which has all kinds of letters, special characters etc in it?

(probable cause of error, right?)

like image 367
Solo Avatar asked Dec 04 '25 15:12

Solo


1 Answers

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">
like image 176
SeinopSys Avatar answered Dec 06 '25 05:12

SeinopSys