Neil
Neil

Reputation: 2519

JavaScript Regex: Replace |b| with <b>

I've got some funky JSON I'm dealing with, the client is sending it with these odd html tags, |b| and |\br| all over the place. So I want to replace them with and
respectively.

I'm trying to run the following str.replace function on the string, but I can't seem to target the pipe characters correctly.

string.replace(/[|b|]/, '<b>');

I've also tried /|b|/, /\|b\|/

Any help is appreciated

Upvotes: 0

Views: 2211

Answers (3)

HamZa
HamZa

Reputation: 14921

You're declaring a character class with [|b|] which means match either b or |. You need to escape the pipes \|b\|since a pipe means "or" in regex.

Upvotes: 2

user1637579
user1637579

Reputation:

The correct regex for replacing |b| with <b> is

/\|b\|/

See: http://jsfiddle.net/vfTG4/

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227200

In regex, [] means "one of these characters", so /[|b|]/ means | OR b.

You want /\|b\|/g. Without the g, it replaces only once.

Upvotes: 2

Related Questions