简体   繁体   中英

How to remove special characters from a string using Javascript

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM