最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - javascript case-insensitive match for part of a string only - Stack Overflow

programmeradmin5浏览0评论

I have the following regex -

bannerHtml.match(/href\s*=\s*[\"']{clickurl}(.*)[\"']/);

which matches the following -
href = "{clickurl}

Now, I want the matching of href only to be case-insensitive, but not the entire string. I checked adding i pattern modifier, but it seems to be used for the entire string always -

bannerHtml.match(/href\s*=\s*[\"']{clickurl}(.*)[\"']/i); 

Further details I want all of the following to match -
hREF = "{clickurl}
href = "{clickurl}
HREF = "{clickurl}

But, capital case clickurl part should not match -
href = "{CLICKURL}

I have the following regex -

bannerHtml.match(/href\s*=\s*[\"']{clickurl}(.*)[\"']/);

which matches the following -
href = "{clickurl}

Now, I want the matching of href only to be case-insensitive, but not the entire string. I checked adding i pattern modifier, but it seems to be used for the entire string always -

bannerHtml.match(/href\s*=\s*[\"']{clickurl}(.*)[\"']/i); 

Further details I want all of the following to match -
hREF = "{clickurl}
href = "{clickurl}
HREF = "{clickurl}

But, capital case clickurl part should not match -
href = "{CLICKURL}

Share Improve this question asked Feb 20, 2013 at 6:40 Sandeepan NathSandeepan Nath 10.3k18 gold badges91 silver badges156 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You can use:

/[hH][rR][eE][fF]\s*=\s*[\"']{clickurl}(.*)[\"']/

The part that changed is: [hH][rR][eE][fF], which means:

Match h or H, followed by r or R, followed by e or E, and followed by f or F.


If you want to make it generic, you can create a helper function that will receive a text string like abc and will return [aA][bB][cC]. It should be pretty straightforward.

You can't make it partially case-sensitive, but you can always be specific:

bannerHtml.match(/[hH][rR][eE][fF]\s*=\s*["']{clickurl}(.*)["']/);

The alternative to this is to discard false matches using a secondary regular expression.

As a note, it's not required to escape quote characters " as only the slash / is the delimiter.

First of all I must say that's a very good question. I thought of 2 solutions to your problem:

  1. make all href strings in lowercase:

    bannerHtml.replace(/href/ig,"href")

  2. First of all I wrapped {clickurl} with parentheses for later use: ({clickurl}). Then, I matched the whole case insensitive string to see if it matches the pattern. Lastly, I checked the {clickurl} string match which is stored in result[1] and see if its in the exact case.

    var re=/href\s*=\s*[\"']({clickurl})(.*)[\"']/i;
    
    var result = re.exec(bannerHtml);
    
    if(result && result[1]=="{clickurl}"){
        //Match!
    }
    

I know its not very regex solution but I that's the best I could think about. Good luck.

发布评论

评论列表(0)

  1. 暂无评论