Home > OS >  Regex to replace newlines not working on nodejs as intended
Regex to replace newlines not working on nodejs as intended

Time:05-17

I have regex which I have tested on regex101 however when I use the same in nodejs it does not replace the newlines. The regex is /([ ]*\n) /gm. It is supposed to replace multiple newlines with a single newline. The code is as follows. This code is a part of my vscode extension. Can someone tell me what I am doing wrong?

function format(str) {
    const regex = /([ ]*\n) /gm;
    const subst = `\n`;
    const result = str.replace(regex, subst);
    return result;
}

function format(str) {
  const regex = /([ ]*\n) /gm;
  const subst = `\n`;
  const result = str.replace(regex, subst);
  return result;
}


console.log(format(`abc
      
d

s




  

             

s`));

CodePudding user response:

Most probably that problem is related to CRLF line endings.

You can use

str.replace(/(?:\s*\n) /g, '\n')

Note you do not need m flag here.

See the JavaScript demo:

const str = "abc\r\n      \r\nd\r\n\r\ns\r\n\r\n\r\n\r\n\r\n  \r\n\r\n             \r\n\r\ns";
console.log(str.replace(/(?:\s*\n) /g, '\n'));

const str2 = "abc\n      \nd\n\ns\n\n\r\n\r\n\n  \n\r\n             \n\ns";
console.log(str2.replace(/(?:\s*\n) /g, '\n'));

  • Related