Reputation: 12129
I am trying to remove special characters from a string if they are on their own and not part of a word.
example would be
var str = "This i$ @ gr£@t t£$t !: i think i$nt it%";
should become
var newstr = "This i$ gr£@t t£$t i think i$nt it%";
Upvotes: 0
Views: 75
Reputation: 43166
You can use this pattern:
^[^\w\s]+\B\s*|\s+[^\w\s]+\B(\s)\s*|\s*\B[^\w\s]+$
Substitute with $1
. This will collapse the whitespace around the removed word into a single space.
Downside: if you aren't happy with which characters are considered "special characters", you have to modify all three occurences of the character class [^\w\s]
.
Upvotes: 0
Reputation: 10340
Use this pattern:
var str = "This i$ @ gr£@t t£$t !: i think i$nt it%";
var result = str.replace(/(?:^|\s+)\W+(?:\s+|$)/g," ");
document.write(result);
Upvotes: 4