Javascript remove special characters from string -
Javascript remove special characters from string
by on on other

Javascript remove special characters from string

How to remove special character from any string using JavaScript.

We can remove special characters from alpha numeric characters. There are two types of methods we are going to use, one is to remove all special characters including numbers, secondly the one that retains numbers.

Here is a good example of the one that removes special characters and numbers using a regular expression.

Firstly:

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

Secondly: Remove Special character but allow numbers


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

We can also trim our string to remove white spaces at the beginning and at the end


string.trim()