DevonDahon
DevonDahon

Reputation: 8350

Javascript: exclude from regex in replace

In this regex:

let str = "hello 〔world〕,foo、bar。";
str.replace(/(〔(.*?)〕|(、)|(,)|(。))/gi,'<div>$1</div>');

How to exclude these two square brackets "〔" and "〕" from the result ?

In order to get this result:

"hello <div>world</div><div>,</div>foo<div>、</div>bar<div>。</div>"

Upvotes: 0

Views: 217

Answers (1)

Code Maniac
Code Maniac

Reputation: 37755

Instead of using a single group you can use two groups. and in callback based on group you can return the value accordingly

let str = "hello 〔world〕,foo、bar。";
str = str.replace(/〔(.*?)〕|((…)|(。)|(,)|(、))/gi,(match,g1,g2)=>`<div>${g1 ? g1 : g2}</div>`);

console.log(str)

Upvotes: 1

Related Questions