开发者

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, ' ');
开发者_JS百科

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, '');


You need a negative lookahead.

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


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".


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜