【问题标题】:replace empty space with dash only if trailing string仅当尾随字符串时才用破折号替换空格
【发布时间】:2012-04-02 21:56:48
【问题描述】:

我正在使用 regEx 和 replace 方法用破折号替换空格,但我只希望在有以下字符时发生这种情况。例如 如果输入字段看起来像这样,则用破折号替换 temp 和 string 之间的空格

input = "temp string";

如果它看起来像这样,那么它只会删除空白空间

input = "temp  ";

这是我现在的正则表达式替换。但不知道如何检查是否有尾随字符。

input.value.replace(/\s+/g, '-');

【问题讨论】:

标签: javascript jquery regex


【解决方案1】:

这应该可以解决问题: 第一个替换负责尾随空格(如果至少有一个) 第二个执行您原来的替换

str.replace(/\s+$/g,'').replace(/\s+/g, '-');

DEMO

【讨论】:

    【解决方案2】:

    DEMO

    input = $.trim(input.replace(/\b \b/g, '-'));
    

    \b (word boundaries) info

    jQuery.trim() api

    【讨论】:

    • 没有响度,您的答案看起来好多了。
    【解决方案3】:

    /\s+$/ 只查找尾随空格,所以在.value 之后添加.replace(/\s+$/, '')

    【讨论】:

    • 我在上面代码的末尾添加了这个,它仍然只是添加了破折号
    猜你喜欢
    • 2019-09-11
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多