3

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

1
  • 2
    don't use blacklists, they will always let you down because of escaping, wierdo encoding, etc. use a char whitelist (with ranges). Commented Mar 4, 2016 at 18:49

1 Answer 1

12

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.
Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.