0

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>"
2
  • I would call the replace method 2 times. One for replacing the unwanted chars with nothing. Commented Apr 6, 2019 at 3:23
  • @undefined why not use the callback function of replace instead of calling it twice, i will go for callback function of replace as we can save extra work Commented Apr 6, 2019 at 3:28

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.