【问题标题】:Strip everything but letters and numbers and replace spaces that are in the sentence with hyphens去掉除字母和数字之外的所有内容,并用连字符替换句子中的空格
【发布时间】:2018-05-07 12:49:48
【问题描述】:

所以我试图解析一个类似于 StackOverflow 标签工作方式的字符串。所以字母和数字是允许的,但其他一切都应该被剥离。空格也应该用连字符代替,但前提是它们在单词内部并且前面没有不允许的字符。

这就是我现在拥有的:

label = label.trim();
label = label.toLowerCase();
label = label.replace(/[^A-Za-z0-9\s]/g,'');
label = label.replace(/ /g, '-');

这可行,但有一些注意事项,例如:

 / this. is-a %&&66 test tag    .   <-- (4 spaces here, the arrow and this text is not part of the test string)

变成:

-this-is-a66-test-tag----

预期:

this-is-a66-test-tag

我查看了这个以获得我现在所拥有的:

How to remove everything but letters, numbers, space, exclamation and question mark from string?

但就像我说的那样,它并没有完全满足我的需求。

如何调整我的代码以提供我想要的东西?

【问题讨论】:

  • 在最后一个 replace 之前只是 trim() labellabel = label.trim().replace(/\s+/g, '-');
  • 或者把最后一行改成label = label.replace(/\s+/g, '-');
  • @gurvinder372 是的,\s+ 是正确的(编辑了我的顶级评论),但仍然需要 trim() 以避免前导/尾随 -s
  • @WiktorStribiżew 同意,否则会有一个尾随 -
  • 嗯,经过测试,似乎预期的结果并不清楚。我得到this-isa-66-test-tag,而this-is-a66-test-tag 是预期的。为什么?请注意,现有的- 与第一个replace 一起被删除。如果您在第一个正则表达式的末尾添加-,您可能会得到this-is-a-66-test-tag。好点了吗?

标签: javascript regex


【解决方案1】:

您需要进行 2 处更改:

  • 由于您没有用第一个replace 替换所有空格,因此您需要用第二个正则表达式替换所有空格字符(因此,必须用\s 替换纯空格,甚至更好,用\s+ 替换替换多个连续出现),
  • 要最后去掉前导/尾随连字符,请在第一次替换后使用trim()

所以,实际的修复会是这样的

var label = " / this. is-a %&&66 test tag    .   ";
label = label.replace(/[^a-z0-9\s-]/ig,'')
  .trim()
  .replace(/\s+/g, '-')
  .toLowerCase();
console.log(label); // => this-isa-66-test-tag

请注意,如果您将- 添加到第一个正则表达式/[^a-z0-9\s-]/ig,您还将在输出中保留原始连字符,并且对于当前测试用例,它将看起来像this-is-a-66-test-tag

【讨论】:

  • 据我所知似乎涵盖了所有情况,谢谢:)
【解决方案2】:

在使用连字符更改所有空格之前使用trim

你可以使用这个功能:

function tagit(label) {
label = label.toLowerCase().replace(/[^A-Za-z0-9\s]/g,'');
return label.trim().replace(/ /g, '-'); }

var str = 'this. is-a %&&66 test tag    .'

console.log(tagit(str));
//=> "this-isa-66-test-tag"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-16
    • 2012-10-24
    • 2014-03-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    相关资源
    最近更新 更多