Home > front end >  In Javascript, How can I replace all blank lines in comments with other characters
In Javascript, How can I replace all blank lines in comments with other characters

Time:07-13

This is the previous code

/*


hello
*/


const x = 'test'

after replacement, it looks like this, I just replaced blank lines in comments

/*
test
test
hello
*/


const x = 'test'

CodePudding user response:

We can try a regex replacement with the help of a callback function:

var input = `/*


hello
*/


const x = 'test'`;

var output = input.replace(/(\/\*.*?\*\/)/gs, (x, y) => y.replace(/^\n/gm, "test\n"));
console.log(output);

The idea here is match every /* ... */ multiline block comment. We then pass each such match to a callback function which does a global replacement on ^\n, which is every empty line, replacing with test\n.

CodePudding user response:

Empty lines can be found using ^$ and a multiline flag:

var s = `/*


hello
*/`

const r = 'test';
console.log(s.replace(/^$/gm, r))

  • Related