【发布时间】: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()label。label = 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