IfOnly
IfOnly

Reputation: 540

Optimize given regular expression in javascript

Following regex replaces " >" or " > " or "> " character with "/".

tempKeyword = tempKeyword.replace(/( > )|( >)|(> )/g,'/');

How can I make this better?

Thanks!

Upvotes: 2

Views: 161

Answers (2)

Toto
Toto

Reputation: 91415

Have a try with this one:

tempKeyword = tempKeyword.replace(/\s*>\s*/g,'/');

Edit 2 according to comment below:

tempKeyword = tempKeyword.replace(/(?:^|\S+\s)>(?:\s\S+|$)/g,'/');

Upvotes: 4

woutervs
woutervs

Reputation: 1510

You can make your regular expression like so:

/ ?> ?/g

What we do here is saying if you find > with 0 or 1 space before then match. (the ? operator stands for 0 or 1)

Upvotes: 2

Related Questions