简体   繁体   中英

remove special characters from a string if they are on their own and not part of a word

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%";

Use this pattern:

 var str = "This i$ @ gr£@tt£$t !: i think i$nt it%"; var result = str.replace(/(?:^|\\s+)\\W+(?:\\s+|$)/g," "); document.write(result); 

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.

Demo.

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

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