Script to split a JS comma-separated var declaration into multiple var declarations

I have a large code base with a ton declared like this:

var x = 1,
y = {
     //some object
},
z = function(arg) {
    // some function
};

I would like to run a node script to convert it all to

var x = 1;
var y = {
   //some object
};
var z = function(arg) {
   // some function
};

It's not as simple as running a regular expression on it, because as soon as an object or function appears, you can no longer search for commas and semicolons.

Is there an existing library or tool that can do this conversion for me? Without trying to minimize or guess the code, I just want to modify the existing, human-readable code to get rid of the comma-separated var declarations.

+4
source share
3 answers

, ,, identifier, = var? , =, , , .

, , . :

,\s*([\$a-z_][\$a-z_0-9]*)(?=\s*=[^=])

. Visual Studio Resharper . , , Resharper .

+1

, - , , :

replace(/,\n/g, ';\nvar ');

:

// in node, this would come straight from a file
var string = 'var x = 1,\ny = {\n  //some object \n},\nz = function(arg) {\n  // some function\n};';

// heres an element we can use for results
var code = document.getElementById('code');

// lets show original string
code.innerHTML = string;

// lets show the new string in a couple of seconds
setTimeout( function () {
  
  // the regex replace
  var updated = string.replace(/,\n/g, ';\nvar ');

  // updating the code element
  code.innerHTML = updated;
  
  // change color to signify finished
  code.className = 'done';
  
}, 2000);
code {
  
  white-space: pre-wrap;
  white-space: -moz-pre-wrap;
  white-space: -o-pre-wrap;
  word-wrap: break-word;
  
}

.done {
  
  background-color: #C0D9AF;  
  
}
<code id="code"></code>
+1

This seems like a trick:

jsfmt --rewrite "a = b, c = d → var a = b; var c = d;" input.js> output.js

input.js:

var x = 1,
y = {
     //some object
},
z = function(arg) {
    // some function
};

output.js:

var x = 1;
var y = {
    //some object
  };
var z = function(arg) {
    // some function
  };

using jsfmt

+1
source

Source: https://habr.com/ru/post/1622286/


All Articles