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
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
Share Improve this question edited Mar 4, 2016 at 20:10 Eloy Pineda 2,18717 silver badges22 bronze badges asked Mar 4, 2016 at 18:33 user545359user545359 4136 gold badges16 silver badges29 bronze badges 1- 2 don't use blacklists, they will always let you down because of escaping, wierdo encoding, etc. use a char whitelist (with ranges). – dandavis Commented Mar 4, 2016 at 18:49
1 Answer
Reset to default 12Try 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.