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

时间:2022-08-22 12:59:43

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

我想删除所有特殊字符,除了使用JavaScript的字符串以外的空间。

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

例如,abc的测试#s应该输出为abc测试。

8 个解决方案

#1


184  

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:

您应该使用string replace函数,使用一个regex。假设有特殊的字符,你的意思是任何不信的东西,这里有一个解决方案:

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

#2


64  

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, '');

#3


22  

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

第一个解决方案对任何UTF-8 alphaben都不起作用。(它将文本如Привіт)。我已经创建了不使用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;
}

#4


8  

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非常有创意的解决方案,但发现它也把数字当作特殊字符来处理,这并不适合我的需要。这是我对海鸥的解决方案(失败安全)的调整……

//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 '';
}

#5


6  

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

我不知道JavaScript,但是使用regex难道不可能吗?

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中查找语法是一个问题。

#6


2  

search all not (word characters || space):

搜索所有不(文字字符||空间):

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

#7


0  

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

dot(.)可能不被认为是特殊的。我在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 '';
}

#8


-7  

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码进行比较,并重新生成一个新的字符串。

#1


184  

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:

您应该使用string replace函数,使用一个regex。假设有特殊的字符,你的意思是任何不信的东西,这里有一个解决方案:

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

#2


64  

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, '');

#3


22  

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

第一个解决方案对任何UTF-8 alphaben都不起作用。(它将文本如Привіт)。我已经创建了不使用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;
}

#4


8  

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非常有创意的解决方案,但发现它也把数字当作特殊字符来处理,这并不适合我的需要。这是我对海鸥的解决方案(失败安全)的调整……

//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 '';
}

#5


6  

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

我不知道JavaScript,但是使用regex难道不可能吗?

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中查找语法是一个问题。

#6


2  

search all not (word characters || space):

搜索所有不(文字字符||空间):

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

#7


0  

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

dot(.)可能不被认为是特殊的。我在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 '';
}

#8


-7  

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码进行比较,并重新生成一个新的字符串。