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

2
  • 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?) Commented Jan 16, 2019 at 5: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. Commented Jan 16, 2019 at 5:43

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Same answer as above