user1513244
user1513244

Reputation: 11

How to select every second occurrence using regular expression

I'm writing jquery code which would remove every second occurrence of character " | " in the code.

Having troubles with writing regular expression for it.

How to specify every second occurrence of " | " using regular expressions?

Upvotes: 1

Views: 2980

Answers (3)

Bergi
Bergi

Reputation: 664630

You have to match 2 pipes to do something with (here: remove) every second one.

string.replace(/(\|.*?)\|/g, "$1");

Upvotes: 1

buckley
buckley

Reputation: 14089

Replace

(?<=.*\|.*)\|

With the empty string

This will transform

test  | test  ||  test  |  test  || 
test  |||

to

test  | test    test    test   
test  |

I first interpreted your question as to collapse multiple occurrences of | to 1 which this regex would solve

Replace

\|{2,}

With

|

What language are you using?

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 219936

You'll have to match 2 pipes, and replace the second one:

theString.replace(/\|([^|]*)\|/g, '|$1');

Here's the fiddle: http://jsfiddle.net/CAvT4/

Upvotes: 2

Related Questions