0

Here is an attempt to remove any excessive blank lines in string.

I'm trying to understand why second approach doesn't workfor lines which contains whitespace.

Demo.

var string = `
    foo



    bar (there are whitespaced lines between bar and baz. I replaced them with dots)
    ....................
    .......................
    ...........           
    baz
`;

// It works
string = string.replace(/^(\s*\n){2,}/gm, '\n');

// Why it doesn't work?
var EOL = string.match(/\r\n/gm) ? '\r\n' : '\n';
var regExp = new RegExp('^(\s*' + EOL + '){2,}', 'gm');
string = string.replace(regExp, EOL);

alert(string);
john c. j.
  • 725
  • 5
  • 28
  • 81

1 Answers1

1

Your \s needs to be changed to \\s. Just putting \s is the same as s.

In strings (enclosed in quotes), the backslash has a special meaning. For example, \n is the newline character. There are a couple of others that you may or may not have heard of, e.g. \b, \t, \v. It would be bad language design choice to make only a few defined ones special, and consider the non-existent \s to be an actual backslash and an s, because it would be inconsistent, a source of errors, and not future-proof. That's why, when you want to have a backslash in a string, you escape the backslash to \\.

In your first example, you use / characters to delimit the regular expression. This is not considered a string bound by the above rules.

sneep
  • 1,828
  • 14
  • 19
  • Not *all* `\s` need their backslash doubled. Which one(s) do, and why? – Jongware Apr 22 '18 at 13:56
  • Possible answer why we need 2 backslashes: https://stackoverflow.com/questions/17863066/why-do-regex-constructors-need-to-be-double-escaped – john c. j. Apr 22 '18 at 14:09