Solo
Solo

Reputation: 6957

Use replace() selectively?

I have hierarhical dropdown which has 3+ steps. Im using very convenient WordPress function which uses &nbsp; to fake <optgroup> / hierarchy. Don't tell me to use <optgroup> like everybody else, it doesn't work with more than 2 steps in hierarchy.

Strings in HTML looks something like this:

Colors&nbsp;&nbsp;(21)
&nbsp;&nbsp;Red&nbsp;&nbsp;(7)
&nbsp;&nbsp;&nbsp;Dark&nbsp;&nbsp;(3)
&nbsp;&nbsp;&nbsp;Light&nbsp;&nbsp;(4)
&nbsp;&nbsp;Blue&nbsp;&nbsp;(13)
&nbsp;&nbsp;&nbsp;Dark&nbsp;&nbsp;(5)
&nbsp;&nbsp;&nbsp;Light&nbsp;&nbsp;(8)
&nbsp;&nbsp;Yellow&nbsp;&nbsp;(1)
&nbsp;&nbsp;&nbsp;Light&nbsp;&nbsp;(1)

Which outputs something like this in dropdown:

Colors (21)
  Red (7)
    Dark (3)
    Light (4)
  Blue (13)
    Dark (5)
    Light (8)
  Yellow (1)
    Light (1)

I need to remove the white space before the word when the item is selected.

Im currently using myString.html.replace( /&nbsp;/g,'' ); but it also removes white space between the word and (count).

How to remove the white space only before the word and not between the word and (count)?

Upvotes: 0

Views: 36

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You can use the starts with notation, which will select only &nbsp; at the beginning of the string

myString.html.replace( /^(&nbsp;)+/,'');

Upvotes: 2

Related Questions