user964202
user964202

Reputation: 73

javascript regular expressions using regex is replacing the string with multiple - characters

I currently have a string of text which needs to be modified via jquery.

 >    "space>space"

I currently have the following jquery to do the replacement for me

$('#breadcrumb').html($('#breadcrumb').html().replace(/&[^;]+;/g, ' - '));

I am trying to replace the > with a single - character, however the regex above is simply changing the enter string to --- instead of -

Any help would be greatly appreciated!

Upvotes: 0

Views: 1018

Answers (2)

nnnnnn
nnnnnn

Reputation: 150040

That's because your regular expression:

/&[^;]+;/g

Is looking for:

&      an ampersand, followed by
[^;]+  one or more characters that are not semicolons, followed by
;      a semicolon

So   and > both match the pattern. The g on the end after the second / means do a global replace - if you leave it off then only the first match will be replaced.

You need:

.replace(/>/g, '-')

This changes all instances of > to - while ignoring everything else.

If you specifically want to replace > only if it is surrounded by non-breaking spaces there are several ways to do it, the simplest of which is probably:

.replace(/ > /g, ' - ')

Upvotes: 2

Dave Newton
Dave Newton

Reputation: 160191

replace(/>/g, "-")

You're not replacing > with -, you're replacing anything that starts with & and ends with ;.

The g modifier isn't necessary if there's only one occurrence.

Upvotes: 0

Related Questions