261

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

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

Thomas Orlita
  • 1,554
  • 14
  • 28
nithi
  • 3,725
  • 2
  • 20
  • 18

13 Answers13

550

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, ""));
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
  • 8
    To use this solution on non-latin alphabet please check [this answer](https://stackoverflow.com/a/150078/3765109) out – efkan Aug 04 '17 at 10:28
  • 5
    This will also removed numerical characters! – tech_geek Nov 21 '18 at 14:12
  • 25
    Actually you need this `str.replace(/[^a-zA-Z0-9 ]/g, "");` notice there's a space between 0-9 and ] – Ammar Shah Mar 07 '19 at 10:50
  • 1
    It need some tweak, it didn't remove / or - characters and the first character of camelCase supposed to be in lower case, but this one in uppercase. – Sansun Mar 06 '20 at 13:12
  • 1
    This leaves stuff like: `pspanspanstrongItem SKUstrongnbspspanspanKBRspanspanpp` [This](https://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/) is a bit better. – CodeFinity Jun 28 '20 at 17:45
  • This does not work for Arabic, Chinese, German, French etc special symbols – Eduard Jan 20 '22 at 10:36
  • this does not remove carriage return `\n` – scavenger Dec 05 '22 at 00:30
204

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, '');
Pere
  • 1,647
  • 3
  • 27
  • 52
Lakshmana Kumar D
  • 2,205
  • 1
  • 13
  • 10
35

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.

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

Seagull
  • 3,319
  • 2
  • 31
  • 37
  • Thank you for this quite creative solution. It is much more in line with how languages actually work, since many of us don't consider "Привіт" or "æøå" special characters. Most solutions out there cut any character that isn't part of the English alphabet. – Alex Langberg May 17 '15 at 12:44
  • 1
    Almost the perfect answer for me, but unfortunately it considers Chinese characters to be special characters. – Eric Majerus Nov 20 '16 at 19:33
  • @EricMajerus and hindi too – programmer Dec 17 '16 at 14:23
  • 1
    Be careful, this also considers numbers as special characters. – just_user Feb 08 '18 at 15:04
16

search all not (word characters || space):

str.replace(/[^\w ]/, '')
dovid
  • 6,354
  • 3
  • 33
  • 73
  • perfect! removing all special unicode characters from the string. – abhishake Jul 28 '20 at 06:04
  • This was a nice solution I used for searching through first+last name. It handles accented characters (é) as well. I added a apostrophe to handle names like D'Angelo. – James Sep 29 '21 at 16:07
14

I don't know JavaScript, but isn't it possible using 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.

Jon
  • 2,932
  • 2
  • 23
  • 30
Thiago Moraes
  • 617
  • 1
  • 10
  • 22
10

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 '';
}
Community
  • 1
  • 1
Mozfet
  • 359
  • 3
  • 12
9

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

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

qtmfld
  • 2,916
  • 2
  • 21
  • 36
Shrinivasan
  • 261
  • 4
  • 9
6

With regular expression

let string  = "!#This tool removes $special *characters* /other/ than! digits, characters and spaces!!!$";

var NewString= string.replace(/[^\w\s]/gi, '');
console.log(NewString); 

Result //This tool removes special characters other than digits characters and spaces

Live Example : https://helpseotools.com/text-tools/remove-special-characters

Munna Kumar
  • 377
  • 4
  • 7
0

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

Try this:

const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);
Jared Forth
  • 1,577
  • 6
  • 17
  • 32
-1

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));
sudheer nunna
  • 1,659
  • 15
  • 17
-16

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.

Gaurav Agrawal
  • 4,355
  • 10
  • 42
  • 61