简体   繁体   中英

Replace special characters that appear before and after a word in a string

I need some help with regex that involves international characters. I have a string as followed

var text = "'#'Hello' Mo'nique! ''Привет марина!@¿";

I want special characters to be removed before and after a word but not those special characters in between like this

Hello Mo'nique Привет марина

I have tried

var result = text.replace(/[`~¡!@#$%^&*()_|+\-=¿?;:'",.<>\{\}\[\]\\\/]/g,'');

but that will remove all the special characters and return

Hello Monique Привет марина

Use negative look-ahead assertion with word boundaries to avoid symbols in between two words.

 var text = "'#'Hello' Mo'nique! ''Привет марина!@¿"; var result = text.replace(/(?!\\b.\\b)[`~¡!@#$%^&*()_|+\\-=¿?;:'",.<>\\{\\}\\[\\]\\\\\\/]/g,''); console.log(result); 

Regex explanation here

使用锚点匹配字符串的开头和结尾

^[`~¡!@#$%^&*()_|+\-=¿?;:'",.<>\{\}\[\]\\\/]+|[`~¡!@#$%^&*()_|+\-=¿?;:'",.<>\{\}\[\]\\\/]+$

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