javascript 使用javascript删除除字母数字和空格之外的所有字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14640486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove all characters except alphanumeric and spaces with javascript
提问by Aaron
I like the solution povided by "Remove not alphanumeric characters from string. Having trouble with the [\] character" but how would I do this while leaving the spaces in place?
我喜欢“从字符串中删除非字母数字字符。遇到 [\] 字符有问题”提供的解决方案,但是我将如何在保留空格的同时做到这一点?
I need to tokenize string based on the spaces after it has been cleaned.
我需要在清理后根据空格对字符串进行标记。
回答by Explosion Pills
input.replace(/[^\w\s]/gi, '')
Shamelessly stolen from the other answer. ^
in the character class means "not." So this is "not" \w
(equivalent to \W
) and not \s
, which is space characters (spaces, tabs, etc.) You can just use the literal if you need.
无耻地从另一个答案中窃取。 ^
在字符类中的意思是“不是”。所以这是“not” \w
(相当于\W
)而不是\s
,它是空格字符(空格、制表符等)。如果需要,您可以只使用文字。
回答by Itang Sanjana
I know this is an old thread, but so popular that appears at the top of a Google search. So, as an alternative, the accepted answer and comment from 3limin4t0r inspired me to:
我知道这是一个旧线程,但非常受欢迎,出现在 Google 搜索的顶部。因此,作为替代方案,3limin4t0r 接受的答案和评论启发了我:
.replace(/\W+/g, " ")
IMHO
恕我直言
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>