Remove unwanted characters from string javascript

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.

Remove unwanted characters from string javascript

asked Jul 2, 2011 at 4:52

2

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

Remove unwanted characters from string javascript

SiddAjmera

36.2k5 gold badges62 silver badges103 bronze badges

answered Jul 2, 2011 at 5:01

Petar IvanovPetar Ivanov

89.4k10 gold badges79 silver badges94 bronze badges

6

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,3853 gold badges24 silver badges51 bronze badges

answered Jun 4, 2013 at 9:13

6

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

answered Oct 21, 2014 at 8:54

Remove unwanted characters from string javascript

SeagullSeagull

3,1461 gold badge28 silver badges37 bronze badges

4

search all not (word characters || space):

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

answered Jan 24, 2018 at 19:00

Remove unwanted characters from string javascript

doviddovid

6,2273 gold badges33 silver badges70 bronze badges

2

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,9042 gold badges22 silver badges30 bronze badges

answered Jul 2, 2011 at 5:02

Thiago MoraesThiago Moraes

6171 gold badge10 silver badges22 bronze badges

1

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

answered Feb 17, 2016 at 11:45

Remove unwanted characters from string javascript

MozfetMozfet

3593 silver badges12 bronze badges

1

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,8062 gold badges19 silver badges36 bronze badges

answered Nov 18, 2019 at 15:26

ShrinivasanShrinivasan

2013 silver badges9 bronze badges

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

answered Oct 10, 2020 at 23:59

Remove unwanted characters from string javascript

3

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

answered Sep 6 at 9:30

Remove unwanted characters from string javascript

M K GuptaM K Gupta

1971 silver badge7 bronze badges

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

answered Dec 11, 2017 at 7:54

Try this:

const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);

Remove unwanted characters from string javascript

Jared Forth

1,5175 gold badges18 silver badges30 bronze badges

answered Sep 10, 2020 at 14:32

Remove unwanted characters from string javascript

1

const input = `#if_1 $(PR_CONTRACT_END_DATE) == '23-09-2019' # 
Test27919<> #elseif_1 $(PR_CONTRACT_START_DATE) ==  '20-09-2019' #
Sender539<> #elseif_1 $(PR_ACCOUNT_ID) == '1234' #
AdestraSID<> #else_1#Test27919<>#endif_1#`;
const replaceString = input.split('$(').join('->').split(')').join('<-');


console.log(replaceString.match(/(?<=->).*?(?=<-)/g));

answered Jan 16, 2020 at 10:10

Remove unwanted characters from string javascript

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.

answered Jul 2, 2011 at 4:58

Gaurav AgrawalGaurav Agrawal

4,2829 gold badges41 silver badges60 bronze badges

4

How do I remove unwanted characters from a string?

Example of removing special characters using replaceAll() method.
public class RemoveSpecialCharacterExample1..
public static void main(String args[]).
String str= "This#string%contains^special*characters&.";.
str = str.replaceAll("[^a-zA-Z0-9]", " ");.
System.out.println(str);.

How can I remove a character from a string using JavaScript?

To remove a character from a string, use string replace() and regular expression. This combination is used to remove all occurrences of the particular character, unlike the previous function. A regular expression is used instead of a string along with global property.

How do I remove a specific part of a string in JavaScript?

If you need to remove all occurrences of a substring from a string, use the String. replaceAll method. To remove all occurrences of a substring from a string, call the replaceAll() method on the string, passing it the substring as the first parameter and an empty string as the second.

How do I remove a specific character from a string in regex?

If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")