javascript 正则表达式删除每行开头的空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5799801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:23:06  来源:igfitidea点击:

Regular expression to remove space in the beginning of each line?

javascript

提问by kiran

I want to remove space in the beggining of each line.

我想删除每一行开头的空格。

I have data in each line with a set of spaces in the beginning so data appears in the middle, I want to remove spaces in the beginning of each line.

我每行都有数据,开头有一组空格,所以数据出现在中间,我想删除每行开头的空格。

tmp = tmp.replace(/(<([^>]+)>)/g,"")

How can I add the ^\scondition into that replace()?

如何将^\s条件添加到其中replace()

回答by Kobi

To remove all leading spaces:

要删除所有前导空格:

str = str.replace(/^ +/gm, '');

The regex is quite simple - one or more spaces at the start. The more interesting bits are the flags - /g(global) to replace all matches and not just the first, and /m(multiline) so that the caret matches the beginning of each line, and not just the beginning of the string.

正则表达式非常简单——开头有一个或多个空格。更有趣的位是标志 - /g(全局)替换所有匹配项而不仅仅是第一个,和/m(多行)以便插入符匹配每一行的开头,而不仅仅是字符串的开头。

Working example: http://jsbin.com/oyeci4

工作示例:http: //jsbin.com/oyeci4

回答by Gabriel

var text = "          this is a string         \n"+
           "    \t    with a much of new lines     \n";
text.replace(/^\s*/gm, '');

this supports multiple spaces of different types including tabs.

这支持不同类型的多个空格,包括制表符。

回答by BraedenP

If all you need is to remove one space, then this regex is all you need:

如果您只需要删除一个空格,那么这个正则表达式就是您所需要的:

^\s

So in JavaScript:

所以在 JavaScript 中:

yourString.replace(/(?<=\n) /gm,"");