javascript - 删除正则表达式末尾的额外空格?

标签 javascript regex actionscript-3

我正在使用此代码来缩进文本 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 ]*)(.+)$

See it in action

或者使匹配从每行的开头开始:

^([\t ]*)(.*)$

See it in action

关于javascript - 删除正则表达式末尾的额外空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34761935/

相关文章:

ruby - 如何grep数组中与另一个数组中的模式匹配的元素?

python - 在 Python 中将字符串转换为所有非字母数字字符的列表

actionscript-3 - 在 AS3 中获取宽度、高度、沿 3D 空间对象的位置

ios - FDT 无法为 iOS 编译 "compile-abc: Permission denied"

apache-flex - 绑定(bind)存在 ActionScript 中的属性

javascript - ExtJS : Multiple form objects in a grid cell

javascript - react 字符串替换 : trouble formatting bold/italic/underline text with capture group regex

regex - 用于嵌套组和捕获标记的 Matlab 正则表达式

javascript - Discord.js UnhandledPromiseRejectionWarning : TypeError: message. guild.channels.cache.array.forEach 不是函数

javascript - 通用汽车 : resize image if it is wider than 1000px