0

How to add a span tag to wrap the other string not in regex?

// This is english & some <span>中文</span> character <span>字元</span>.

var str = 'This is english & some 中文 character 字元.'

var pattern = new RegExp(/[a-zA-Z0-9 _^!-~-]/);
console.log( pattern.test(str));
user1775888
  • 3,147
  • 13
  • 45
  • 65

1 Answers1

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

Community
  • 1
  • 1
Salman A
  • 262,204
  • 82
  • 430
  • 521