-1

I need to remove all special characters from string using Javascript but its unable to remove. Please find my code below.

function checkString(){
      var sourceString='a|"bc!@£de^&$f g';
      var outString = sourceString.replace(/[`~!@#$%^&*()|+\-=?;:'",<>\{\}\[\]\\\/]/gi, '');
      console.log('sourcestring',outString);
}

Here I could not get the expected output. I am getting this abc£def g in console. Here I need to remove all special characters. Please help me to resolve this issue.

  • You might consider using a character set *whitelist* instead, if you can, otherwise you'll have lots and lots of characters to specify. (is a whitelist an option?) – CertainPerformance Jan 16 '19 at 05:33
  • It's because you are not removing the pound sign. Which leads to what @CertainPerformance said - if you are trying to blacklist, you need to keep adding more and more symbols, and it becomes unfeasable. – VLAZ Jan 16 '19 at 05:43

2 Answers2

1

Use regex:

var sourceString='a|"bc!@£de^&$f g';

console.log("Before: " + sourceString);
sourceString = sourceString.replace(/[^a-zA-Z0-9 ]/g, "");
console.log("After: " + sourceString);

It essentially removes everything but alphabet and numbers (and spaces).

Aniket G
  • 3,471
  • 1
  • 13
  • 39
0

Remove every thing except numbers and letters.

var sourceString='a|"bc!@£de^&$f g';
     // var outString = sourceString.replace(/[`~!@#$%^&*()|+\-=?;:'",<>\{\}\[\]\\\/]/gi, '');
   var outString = sourceString.replace(/[^a-zA-Z0-9]/g, '');
      console.log('sourcestring',outString);
AJAY MAURYA
  • 541
  • 3
  • 11