Seth Duncan
Seth Duncan

Reputation: 1265

Regular Expression to Exclude First Item

I have a div that I am trying to run a regular expression on

<div class="module-header-content module-default">

I am using this replace operation that used to work,but now that I have added the module-header-content class it becomes problematic

replace(/module-\w+/gi, ' ');

I need a regular expression that removes all instances of module- except for module-header-content

Any help.

Thanks

The entire call:

        var $target = $(this).parent().parent().parent().parent();


        //// Removes all module-xxxx classes
        var classes = $target[0].className.replace(/module-\w+/gi, '');

Upvotes: 4

Views: 982

Answers (3)

bowsersenior
bowsersenior

Reputation: 12574

Expanding on masher's answer, lots of programmers know about using parentheses to get matches within a regex, but the very useful non-matching parentheses are not as well known.

/(foo)/ will match foo and store it in the matches array. But what if you don't want a match to be stored? In that case, you can use ?: inside the parentheses: /(?:foo)/ . This will match the pattern but not store it in the matches array.

You can also search for anything except what is inside the parentheses with ?! so /(?!foo)/ will match anything except 'foo'. If you wanted to store the match, you'd use /[^(foo)]/ .

Yes, regular expressions are wonderful.

Upvotes: 2

GodFather
GodFather

Reputation: 3166

Try this:

str = "module-header-content module-default module-default-foo module-default-foo-bar";
str.replace(/module(?!-header)(-\w+)*/gi, '');

It'll get all classes except "module-header-content".

Upvotes: 2

masher
masher

Reputation: 4116

You need a negative lookahead.

module-(?!header-content)\w+

Upvotes: 5

Related Questions