How to remove special characters from a string using Javascript

19,437

Try with this function:

function removeSpecialChars(str) {
  return str.replace(/(?!\w|\s)./g, '')
    .replace(/\s+/g, ' ')
    .replace(/^(\s*)([\W\w]*)(\b\s*$)/g, '$2');
}
  • 1st regex /(?!\w|\s)./g remove any character that is not a word or whitespace. \w is equivalent to [A-Za-z0-9_]
  • 2nd regex /\s+/g find any appearance of 1 or more whitespaces and replace it with one single white space
  • 3rd regex /^(\s*)([\W\w]*)(\b\s*$)/g trim the string to remove any whitespace at the beginning or the end.
Share:
19,437
user545359
Author by

user545359

Updated on July 21, 2022

Comments

  • user545359
    user545359 almost 2 years

    Could someone please help me to remove special characters from a string using javascript or Jquery.

    Note: I would like to remove only a specific set of special characters but not replacing it with any character. Below is the code i am trying. Thanks in advance.

    Code:

    filename = filename.replace(/[&\/\\#,+()$~%'":*?<>{}|]/g, '').replace(/\u201C/g, '').replace(/\u201D/g, '').replace(/\s+/g, '');
    

    Sample string Name:

    Test5 & special~, #, %, & , ,, , , , , , , , “”

    Actual Result:

    (Test5 space special-----------------------spaces till here)

    Expected Result:

    Test5 special

  • user545359
    user545359 about 8 years
    Thank you @Eloy. Your solution worked perfectly. I am also trying to replace some special characters that are unicode (.replace(/\u201C/g, '').replace(/\u201D/g, '')). Could you please let me know how to include in your regex.
  • Eloy Pineda
    Eloy Pineda about 8 years
    @user545359 I edited the answer to address your comment and dandavis comment. He is right, it is better to use whitelist instead of blacklist. Please let me know if this work for you.