Helge
Helge

Reputation: 833

Regexp to replace & but not < and >

I'd like to use JS (and regex?) to replace all & with &, EXCEPT those & characters that are related to

>

and

<

Can anybody please help? :) Thanks in advance!

Upvotes: 0

Views: 737

Answers (2)

Qtax
Qtax

Reputation: 33908

You could use a regex like:

&(?!amp;|gt;|lt;)

JS example:

"test & > < and & with &foo;".replace(/&(?!amp;|gt;|lt;)/gi, "&");

Result:

"test & > < and & with &foo;"

Upvotes: 2

Kendall Frey
Kendall Frey

Reputation: 44316

Simplest solution is to check for letters and a semicolon following the &

/&(?![A-Z]+;)/gi

A complete standards-compliant version that also checks for numeric codes:

/&(?!([A-Za-z]+|#\d+|#x[\da-fA-F]+);)/g

Upvotes: 3

Related Questions