我正在使用此代码来缩进文本 block 。它工作正常,但它在末尾添加了空白。
public var indentPattern:RegExp = /([\t ]*)(.*)$/gm;
public function indent(input:String, indentAmount:String = "\t"):String {
if (input==null || input=="") return indentAmount;
var indentedText:String = input.replace(indentPattern, indentAmount + "$1$2");
return indentedText;
}
测试输入数据:
<style type="text/css">
html, body {
height:100%;
margin:0;
padding:0;
line-height:.8;
}
*, *:before, *:after {
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
box-sizing:border-box;
}
</style>
实际输出:
<style type="text/css">
html, body {
height:100%;
margin:0;
padding:0;
line-height:.8;
}
*, *:before, *:after {
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
box-sizing:border-box;
}
</style>
注意:当我说末尾的空白时,制表符会添加到行尾分号之后。尝试突出显示页面上的文本,看看我在说什么。
最佳答案
问题在于
([\t ]*)(.*)$
可以匹配空字符串。因此,在行尾匹配一个空字符串,并将 indentAmount
放置在那里。将其更改为:
([\t ]*)(.+)$
或者使匹配从每行的开头开始:
^([\t ]*)(.*)$
关于javascript - 删除正则表达式末尾的额外空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34761935/