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

2020/10/26 17:43 · javascript ·  · 0评论

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

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

您应该使用带有单个正则表达式的字符串替换功能。假设使用特殊字符,您的意思不是字母,这是一种解决方案:

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

您可以指定要删除的字符来执行此操作:

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

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

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

第一种解决方案不适用于任何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;
}

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

更新2:在进行模糊搜索时,我采用了原始的解决方案。如果您还尝试删除特殊字符以实现搜索功能,则有更好的方法。使用任何音译库,该只会从拉丁字符中产生字符串,然后简单的Regexp就可以消除所有特殊字符。(这也适用于中文,并且使用Tromsø==也将获得附带好处Tromso)。

我不懂JavaScript,但是使用正则表达式不可行吗?

诸如[^\w\d\s]数字,字符和空格之类的东西将与之匹配。在JavaScript中找到语法只是一个问题。

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...

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

search all not (word characters || space):

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

Try to use this one

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

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

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

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 '';
}
const input = `#if_1 $(PR_CONTRACT_END_DATE) == '23-09-2019' # 
Test27919<alerts@imimobile.com> #elseif_1 $(PR_CONTRACT_START_DATE) ==  '20-09-2019' #
Sender539<rama.sns@gmail.com> #elseif_1 $(PR_ACCOUNT_ID) == '1234' #
AdestraSID<hello@imimobile.co> #else_1#Test27919<alerts@imimobile.com>#endif_1#`;
const replaceString = input.split('$(').join('->').split(')').join('<-');


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

Try this:

const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);
const str = "abc's@thy#^g&test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));

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.

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.

本文地址:http://javascript.askforanswer.com/shiyongjavascriptcongzifuchuanzhongshanchuchukonggeyiwaidesuoyouteshuzifu.html
文章标签: ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!