Src
Src

Reputation: 5482

Split with RegExp group

I need to replace word WUB from any string which can contain many WUB words following together. Example: WUBHelloWUBWUBitsWUBmeWUB must become Hello its me

I decided to use split with RegExp:

'WUBHelloWUBWUBitsWUBmeWUB'.split(/(WUB)+/g).join(" ").split(/\s{2,}/g).join(" ").trim()

But when i'm using roud brakets (WUB)+ to match WUB from 1 to unlimited times - it doesn't work.

Upvotes: 1

Views: 52

Answers (1)

revo
revo

Reputation: 48711

split() function includes capturing groups in result set to avoid this behavior you have to use non-capturing groups:

(?:WUB)+

You don't need split() even:

'WUBHelloWUBWUBitsWUBmeWUB'.replace(/(?:WUB)+/g, " ").trim();

Upvotes: 4

Related Questions