user1775888
user1775888

Reputation: 3303

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

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));

Upvotes: 0

Views: 526

Answers (1)

Salman Arshad
Salman Arshad

Reputation: 272106

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.

Upvotes: 1

Related Questions