views:

135

answers:

2

In Javascript,

str = 'left ui-tabs ui-widget ui-widget-content center right';

Is it possible to remove non 'ui-*' words by invoking str.replace() with regexp ?

The result after invoking str.replace() should be:

str.replace(/ /, '') = 'ui-tabs ui-widget ui-widget-content';

I've tried some regexp patterns, but they doesn't work.

+3  A: 

Could try something like:

str.match(/ui-[\w-]+/g).join(" ")
illvm
Works fine. However there is an assumption that the words in the original string are split by a single space. If that were not true, the join() result won't be the same as that which the user expects after removing the non 'ui-' words.
Vijay Dev
This assumption seems appropriate being that `str` in this example is likely the contents of some DOM node's `className` attribute, and that Kieran is looking to do some unobtrusive widget configuration via that attribute.
Justin Johnson
@Vijay Dev: that's right, but it really doesn't matter. those are class names. some are jquery ui classes. joining on a single space achieves the same result. and if you look at what the asker wants, this achieves it quite well.
geowa4
@Justin, @George: Agreed. The context of the usage makes the whitespaces irrelevant.
Vijay Dev
+2  A: 

Does it have to be a regex? You could do it this way, but split/join seems like a better candidate here.

Joel Coehoorn