简体   繁体   English

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

[英]Remove all special characters except space from a string using JavaScript

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 test#s应该 output as abcs tests

You should use the string replace function, with a single regex.您应该使用单个正则表达式替换 function 字符串。 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, ""));

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

The first solution does not work for any UTF-8 alphabet.第一个解决方案不适用于任何 UTF-8 字母表。 (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.我设法创建了一个不使用 RegExp 的 function 并在 JavaScript 引擎中使用良好的 UTF-8 支持。 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.唯一的例外是空格。

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.更新 2:我在进行模糊搜索时找到了原始解决方案。 If you also trying to remove special characters to implement search functionality, there is a better approach.如果您还尝试删除特殊字符以实现搜索功能,则有更好的方法。 Use any transliteration library which 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 ). (这也适用于中国人,您还可以通过制作Tromsø == Tromso获得附带好处)。

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. [^\w\d\s]之类的内容将匹配除数字、字符和空格之外的任何内容。 It would be just a question to find the syntax in JavaScript.在 JavaScript 中找到语法只是一个问题。

search all not (word characters || space):搜索所有不(单词字符||空格):

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

I tried Seagul's very creative solution, but found it treated numbers also as special characters, which did not suit my needs.我尝试了 Seagul 非常有创意的解决方案,但发现它也将数字视为特殊字符,这不符合我的需要。 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 '';
}

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 [^]表示否定, \w表示[a-zA-Z0-9_]单词字符, \s表示空格, /[]/g表示全局

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

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

Try this to achieve the same results I have a sample here, you can edit it or make it more efficient:试试这个以获得相同的结果我在这里有一个示例,您可以对其进行编辑或使其更高效:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Validation example</title>
</head>

<body>
    <div>
        <!-- optional form element for HTML5 Validation on submit 
            - the Vanilla js code below can work well without a form element 

            =====================================================
            So you can decide to use the HTML5 validation on top of JS validation when you use a form with a submit button
            But if you use the input element only then you have to rely on the js validation only
        -->
        <form id="search-form">
            <input type="text" pattern="[A-Za-z\s0-9]{3,}" title="Only letters, numbers and spaces are allowed" placeholder="Search" name="search" id="search-input">
            <!-- optional submit button if using a form -->
            <button type="submit">Submit</button>
        </form>
    </div>
    <script>
        window.onload = function () {
            var inputElementRef = document.getElementById("search-input"); //use id selector for precise selection in a large html document
            var inputSearchValue = "";
            inputElementRef.addEventListener("keydown", function (e) {
                inputSearchValue = e.target.value;
                // replace invalid characters if you are not using HTML5 validation this will ensure the value 
                //  is always the expected string format
                inputSearchValue = inputSearchValue.replace(/[^a-zA-Z\s]/g,"");

            });
            // whenever you change the value you can retrieve it from var inputSearchValue
            // For example
            var handleFormSubmit = function (e) {
                e.preventDefault();
                console.log('inputSearchValue', inputSearchValue)
            }
            var optionalSearchFormRef = document.getElementById("search-form");
            optionalSearchFormRef.addEventListener("submit", handleFormSubmit);
        }
    </script>
</body>

</html>

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 替换 function 以删除所有特殊字符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM