【问题标题】:RegEx to Remove Trailing Space正则表达式删除尾随空格
【发布时间】:2016-02-24 05:28:42
【问题描述】:

我有以下正则表达式:

$('.my-selector').each(function(){
  var t = $(this).text(),
      id = t.toLowerCase().replace(/\s+/g, '-');
  id  = id.replace(/[^a-zA-Z0-9-]/g, "");
});

这会用- 替换所有空格,然后删除任何不是a-z0-9- 的字符。这可行,但我注意到一件事,如果我有一个尾随空格,它就会变成-。举些例子。 My (test) string 变为 my-test-string-

如何从字符串的末尾删除最后一个-(或)?

【问题讨论】:

标签: javascript regex


【解决方案1】:

最简单的选择是在替换空格之前链接.trim() method。这样做会删除尾随空格。

string.toLowerCase().trim().replace(/\s+/g, '-')

它会输出my-test-string:

var text = 'My (test) string ';
var id = text.toLowerCase().trim().replace(/\s+/g, '-')
             .replace(/[^a-zA-Z0-9-]/g, '');

console.log(id); // my-test-string

当然,您也可以只使用负前瞻来防止末尾的空格被替换:

string.toLowerCase().replace(/\s+(?!\s*$)/g, '-')

【讨论】:

    【解决方案2】:

    试试

    $('.my-selector').each(function(){
      var t = $(this).text(),
          id = t.toLowerCase().replace(/\s+/g, '-');
      id  = id.replace(/[^a-zA-Z0-9-]/g, "").replace(/-$/, '');
    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-20
      • 1970-01-01
      • 2012-02-24
      • 1970-01-01
      • 2019-03-10
      • 1970-01-01
      • 1970-01-01
      • 2020-07-20
      相关资源
      最近更新 更多