【发布时间】:2013-01-16 10:08:06
【问题描述】:
我喜欢“Remove not alphanumeric characters from string. Having trouble with the [\] character”提供的解决方案,但我将如何在保留空间的同时做到这一点?
我需要在清理后根据空格对字符串进行标记。
【问题讨论】:
标签: javascript regex
我喜欢“Remove not alphanumeric characters from string. Having trouble with the [\] character”提供的解决方案,但我将如何在保留空间的同时做到这一点?
我需要在清理后根据空格对字符串进行标记。
【问题讨论】:
标签: javascript regex
input.replace(/[^\w\s]/gi, '')
无耻地从另一个答案中窃取。字符类中的^ 表示“不是”。所以这是“不是”\w(相当于\W)而不是\s,它是空格字符(空格、制表符等)。如果需要,您可以使用文字。
【讨论】:
[^\w] = \W 和 [^\s] = \S 因此正则表达式可以简化为/[\W\S]/g,不需要忽略大小写修饰符,因为\W 考虑了这些.
我知道这是一个旧线程,但它非常受欢迎,出现在 Google 搜索的顶部。因此,作为替代方案,3limin4t0r 接受的答案和评论启发了我:
.replace(/\W+/g, " ")
恕我直言
const input = document.querySelector("input");
const button = document.querySelector("button");
const output = document.querySelector("output");
button.addEventListener("click", () => {
output.textContent = input.value.replace(/\W+/g, " ");
})
<input>
<button>Replace</button>
<p>
<output></output>
</p>
【讨论】: