正则表达式删除换行符和内容之间的空格

Regex To Remove Spaces Between Newlines and Content

本文关键字:之间 空格 删除 换行符 正则表达式      更新时间:2023-09-26

所以我想删除新行和内容之间的任何空格。

 this
  is
    some
  content
son
          best
  believe

应该变成:

this
is
some
content
son
best
believe

我试过做这样的事情,但它似乎没有解决问题:

string.replace(/^'s*/g, '');

有什么想法吗?

使用多行模式:

string = string.replace(/^'s*/gm, '');

这使得^匹配每行的开头而不是整个字符串。

您可以简单地执行以下操作。

string.replace(/^ +/gm, '');

正则表达式:

^     the beginning of the string
 +    ' ' (1 or more times (matching the most amount possible))

g修饰符表示全局,所有匹配项。m修饰符表示多行。使^$与每行的开头/结尾匹配。

查看示例

您需要

m修饰符,以便^匹配换行符而不是字符串的开头:

string.replace(/^'s*/gm, '');