var str = "This is english & some 中文 character 字元.";
var regex = /([^a-zA-Z0-9 _^!-~-]+)/g;
console.log(str.replace(regex, '<span>$1</span>'));
// This is english & some <span>中文</span> character <span>字元</span>.
I have used your regex with the following changes:
- Added capturing group by adding
()
so that matches can be captured
- Then use the captured group in replacement using
$1
- Added a
g
flag for global which means all matches must be replaced instead of just the first one.
You might be interested in the regular expressions discussed here.