使用 JavaScript 从字符串中删除除空格以外的所有特殊字符

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

Remove all special characters except space from a string using JavaScript

javascriptspecial-characters

提问by nithi

I want to remove all special characters except space from a string using JavaScript.

我想使用 JavaScript 从字符串中删除除空格之外的所有特殊字符。

For example, abc's test#sshould output as abcs tests.

例如, abc's test#s应该输出为 abcs tests.

回答by Petar Ivanov

You should use the string replace function, with a single regex. Assuming by special characters, you mean anything that's not letter, here is a solution:

您应该使用带有单个正则表达式的字符串替换函数。假设通过特殊字符,您的意思是任何不是字母的东西,这是一个解决方案:

const str = "abc's test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));

回答by Lakshmana Kumar D

You can do it specifying the characters you want to remove:

您可以指定要删除的字符:

string = string.replace(/[&\/\#,+()$~%.'":*?<>{}]/g, '');

Alternatively, to change all characters except numbers and letters, try:

或者,要更改除数字和字母以外的所有字符,请尝试:

string = string.replace(/[^a-zA-Z0-9]/g, '');

回答by Seagull

The first solution does not work for any UTF-8 alphabet. (It will cut text such as Прив?т). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.

第一个解决方案不适用于任何 UTF-8 字母表。(它将剪切诸如 Прив?т 之类的文本)。我设法创建了一个不使用 RegExp 并在 JavaScript 引擎中使用良好的 UTF-8 支持的函数。这个想法很简单,如果一个符号的大小写相等,那么它就是一个特殊字符。唯一的例外是空白。

function removeSpecials(str) {
    var lower = str.toLowerCase();
    var upper = str.toUpperCase();

    var res = "";
    for(var i=0; i<lower.length; ++i) {
        if(lower[i] != upper[i] || lower[i].trim() === '')
            res += str[i];
    }
    return res;
}

Update:Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.

更新:请注意,此解决方案仅适用于有小写和大写字母的语言。在像中文这样的语言中,这是行不通的。

Update 2:I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration librarywhich will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Troms?== Tromso).

更新 2:当我进行模糊搜索时,我来到了原始解决方案。如果您还尝试删除特殊字符以实现搜索功能,则有更好的方法。使用任何可以仅从拉丁字符生成字符串的音译库,然后简单的 Regexp 将完成删除特殊字符的所有魔术。(这也适用于china人,你也可以通过制作Troms?==获得额外的好处Tromso)。

回答by Thiago Moraes

I don't know JavaScript, but isn't it possible using regex?

我不懂 JavaScript,但不能使用正则表达式吗?

Something like [^\w\d\s]will match anything but digits, characters and whitespaces. It would be just a question to find the syntax in JavaScript.

类似的东西[^\w\d\s]将匹配除数字、字符和空格之外的任何内容。在 JavaScript 中找到语法只是一个问题。

回答by Mozfet

I tried Seagul's very creative solution, but found it treated numbers also as special characters, which did not suit my needs. So here is my (failsafe) tweak of Seagul's solution...

我尝试了 Seagul 非常有创意的解决方案,但发现它也将数字视为特殊字符,这不符合我的需求。所以这是我对 Seagul 解决方案的(故障安全)调整......

//return true if char is a number
function isNumber (text) {
  if(text) {
    var reg = new RegExp('[0-9]+$');
    return reg.test(text);
  }
  return false;
}

function removeSpecial (text) {
  if(text) {
    var lower = text.toLowerCase();
    var upper = text.toUpperCase();
    var result = "";
    for(var i=0; i<lower.length; ++i) {
      if(isNumber(text[i]) || (lower[i] != upper[i]) || (lower[i].trim() === '')) {
        result += text[i];
      }
    }
    return result;
  }
  return '';
}

回答by dovid

search all not (word characters || space):

搜索所有不是(单词字符 || 空格):

str.replace(/[^\w ]/, '')

回答by Shrinivasan

Try to use this one

尝试使用这个

var result= stringToReplace.replace(/[^\w\s]/gi, '')

here ^ carat is for negation \w for [a-zA-Z0-9_] word characters and \s for space /[]/gi for global

这里 ^ carat 用于否定 \w 用于 [a-zA-Z0-9_] 单词字符和 \s 用于空格 /[]/gi 用于全局

回答by sudheer nunna

const input = `#if_1 $(PR_CONTRACT_END_DATE) == '23-09-2019' # 
Test27919<[email protected]> #elseif_1 $(PR_CONTRACT_START_DATE) ==  '20-09-2019' #
Sender539<[email protected]> #elseif_1 $(PR_ACCOUNT_ID) == '1234' #
AdestraSID<[email protected]> #else_1#Test27919<[email protected]>#endif_1#`;
const replaceString = input.split('$(').join('->').split(')').join('<-');


console.log(replaceString.match(/(?<=->).*?(?=<-)/g));

回答by hassanf1

dot (.) may not be considered special. I have added an OR condition to Mozfet's & Seagull's answer:

点 (.) 可能不被认为是特殊的。我在 Mozfet 和 Seagull 的回答中添加了 OR 条件:

function isNumber (text) {
      reg = new RegExp('[0-9]+$');
      if(text) {
        return reg.test(text);
      }
      return false;
    }

function removeSpecial (text) {
  if(text) {
    var lower = text.toLowerCase();
    var upper = text.toUpperCase();
    var result = "";
    for(var i=0; i<lower.length; ++i) {
      if(isNumber(text[i]) || (lower[i] != upper[i]) || (lower[i].trim() === '') || (lower[i].trim() === '.')) {
        result += text[i];
      }
    }
    return result;
  }
  return '';
}

回答by Gaurav Agrawal

Whose special characters you want to remove from a string, prepare a list of them and then user javascript replace function to remove all special characters.

您想从字符串中删除哪些特殊字符,准备一个列表,然后使用 javascript 替换功能删除所有特殊字符。

var str = 'abc'de#;:sfjkewr47239847duifyh';
alert(str.replace("'","").replace("#","").replace(";","").replace(":",""));

or you can run loop for a whole string and compare single single character with the ASCII code and regenerate a new string.

或者您可以对整个字符串运行循环并将单个字符与 ASCII 代码进行比较并重新生成一个新字符串。