nodejs正则表达式删除空格后的每个换行符

时间:2019-05-02 10:57:57

标签: javascript node.js regex

给出如下字符串:

"hello\n          \n            my dog is red\n          \n          and\n          stripey\n          \n            \n            with spots\n"

我想要这个:

"hello\n                      my dog is red\n                    and\n          stripey\n                                  with spots\n"

1 个答案:

答案 0 :(得分:1)

使用此正则表达式替换

/^[ \t]*\n/mg

带有空字符串,其中^[ \t]*从行首到\n匹配一个或多个空格或制表符,然后将其删除。

查看此JS演示。

var s = 'hello\n          \n            my dog is red\n          \n          and\n          stripey\n          \n            \n            with spots\n';
console.log("Before: " + s)
console.log("After: " + s.replace(/^[ \t]*\n/mg, ''))