Javascript 正则表达式删除所有非字母数字并用 + 替换空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32106243/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:37:20  来源:igfitidea点击:

Regex to remove all non alpha-numeric and replace spaces with +

javascriptregex

提问by sgript

I'm looking to use regex to try remove all non alpha-numeric characters from a string and replace spaces with a +

我正在寻找使用正则表达式来尝试从字符串中删除所有非字母数字字符并用 + 替换空格

All I want to permit is basically alphabetical words A-Z and +

我想允许的基本上是字母 AZ 和 +

This is specifically to prepare the string to become a part of a URL, thus need the + symbols instead of spaces.

这是专门准备字符串成为 URL 的一部分,因此需要 + 符号而不是空格。

I have looked at /\W+/however this removes all white spaces and alpha-numeric characters, whereas I want to leave the spaces in if possible to then be replaced by + symbols.

我已经看过/\W+/但是这会删除所有空格和字母数字字符,而如果可能的话,我想保留空格然后用 + 符号替换。

I've searched around a bit but I can't seem to find something, I was hoping someone might have any simple suggestions for this.

我已经搜索了一下,但似乎找不到任何东西,我希望有人可能对此有任何简单的建议。

Sample string & Desired result:Durarara!!x2 Ten->durarara+x2+ten

示例字符串和所需结果:Durarara!!x2 Ten->durarara+x2+10

回答by Paul Roub

This is actually fairly straightforward.

这实际上相当简单。

Assuming stris the string you're cleaning up:

假设str是您正在清理的字符串:

str = str.replace(/[^a-z0-9+]+/gi, '+');

The ^means "anything not in this list of characters". The +after the [...]group means "one or more". /gimeans "replace all of these that you find, without regard to case".

^意思是“没有任何字符名单”。所述+[...]组的意思是“一个或多个”。/gi意思是“替换你找到的所有这些,不考虑大小写”。

So any stretch of characters that are not letters, numbers, or '+' will be converted into a single '+'.

因此,任何不是字母、数字或“+”的字符都将转换为单个“+”。

To remove parenthesized substrings (as requested in the comments), do this replacement first:

要删除带括号的子字符串(根据评论中的要求),请先执行此替换:

str = str.replace(/\(.+?\)/g, '');

function replacer() {

  var str = document.getElementById('before').value.
    replace(/\(.+?\)/g, '').
    replace(/[^a-z0-9+]+/gi, '+');

  document.getElementById('after').value = str;
}

document.getElementById('replacem').onclick = replacer;
<p>Before:
  <input id="before" value="Durarara!!x2 Ten" />
</p>

<p>
  <input type="button" value="replace" id="replacem" />
</p>

<p>After:
  <input id="after" value="" readonly />
</p>

回答by Praveen reddy Dandu

 str = str.replace(/\s+/g, '+');
 str  = str.replace(/[^a-zA-Z0-9+]/g, "");
  • First line replaces all the spaces with + symbol
  • Second line removes all the non-alphanumeric and non '+' symbols.
  • 第一行用 + 符号替换所有空格
  • 第二行删除所有非字母数字和非“+”符号。