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

javascript - Regex to select whole word if part matches - Stack Overflow

programmeradmin1浏览0评论

I want to be able to select the WHOLE word, before and after the match...

Currently it only selects the part in the word that's matched. So if i'm looking after "Dog" in the word "Doglets" it selects Dog.

I want it to select Doglets. And I also want it to select letsDog if that was the case.

return html.replace(new RegExp('(\\b)(' + query + ')(\\b)', 'ig'), "<span class='search-enlight'>$&</span>");

UPDATE:

function filterSearchWords() {
    var query = $("#searchquery").val();

    go(query);
    function go(query) {
        $.extend($.expr[':'], {
            'containsi': function (elem, i, match, array) {
                return (elem.textContent || elem.innerText || '').toLowerCase()
                .indexOf((match[3] || "").toLowerCase()) >= 0;
            }
        });

        $(".search-result p:containsi(" + query + ")").html(function (_, html) {
            return html.replace(new RegExp('(\\b)( \\w*' + query + '\\w*)(\\b)', 'ig'), "<span class='search-enlight'>$&</span>")
        });
        $(".search-result h2 a:containsi(" + query + ")").html(function (_, html) {
            return html.replace(new RegExp('(\\b)( \\w*' + query + '\\w*)(\\b)', 'ig'), "<span class='search-enlight'>$&</span>")
        });
        console.log(query);
    }
}

It matches full words now, however it does not match with capitalized letters, the i flag seems not to work

HTML:

div class="search-result">
                                <span class="thumb" style="font-family: 'draftit'; float: left;">&#xe811;</span>&nbsp;

                                <h2 class="title"><a href="/produkter/malins-testprodukt/skatteavdrag/berakning-av-skatteavdrag/skatteavdrag-nar-skattesedel-inte-har-lamnats/">Skatteavdrag n&#228;r skattesedel inte har l&#228;mnats</a></h2>
                                <p>
                                    Arbetsgivare f&#229;r fr&#229;n Skatteverket besked om hur skatteavdraget f&#246;r respektive anst&#228;lld ska ber&#228;knas. Se avsnittet  tabellavdrag och CSR-f&#246;rfr&#229;gan . Arbetstagaren beh&#246;ver d&#229; inte l...
                                </p>

                            </div>

I want to be able to select the WHOLE word, before and after the match...

Currently it only selects the part in the word that's matched. So if i'm looking after "Dog" in the word "Doglets" it selects Dog.

I want it to select Doglets. And I also want it to select letsDog if that was the case.

return html.replace(new RegExp('(\\b)(' + query + ')(\\b)', 'ig'), "<span class='search-enlight'>$&</span>");

UPDATE:

function filterSearchWords() {
    var query = $("#searchquery").val();

    go(query);
    function go(query) {
        $.extend($.expr[':'], {
            'containsi': function (elem, i, match, array) {
                return (elem.textContent || elem.innerText || '').toLowerCase()
                .indexOf((match[3] || "").toLowerCase()) >= 0;
            }
        });

        $(".search-result p:containsi(" + query + ")").html(function (_, html) {
            return html.replace(new RegExp('(\\b)( \\w*' + query + '\\w*)(\\b)', 'ig'), "<span class='search-enlight'>$&</span>")
        });
        $(".search-result h2 a:containsi(" + query + ")").html(function (_, html) {
            return html.replace(new RegExp('(\\b)( \\w*' + query + '\\w*)(\\b)', 'ig'), "<span class='search-enlight'>$&</span>")
        });
        console.log(query);
    }
}

It matches full words now, however it does not match with capitalized letters, the i flag seems not to work

HTML:

div class="search-result">
                                <span class="thumb" style="font-family: 'draftit'; float: left;">&#xe811;</span>&nbsp;

                                <h2 class="title"><a href="/produkter/malins-testprodukt/skatteavdrag/berakning-av-skatteavdrag/skatteavdrag-nar-skattesedel-inte-har-lamnats/">Skatteavdrag n&#228;r skattesedel inte har l&#228;mnats</a></h2>
                                <p>
                                    Arbetsgivare f&#229;r fr&#229;n Skatteverket besked om hur skatteavdraget f&#246;r respektive anst&#228;lld ska ber&#228;knas. Se avsnittet  tabellavdrag och CSR-f&#246;rfr&#229;gan . Arbetstagaren beh&#246;ver d&#229; inte l...
                                </p>

                            </div>
Share Improve this question edited Sep 1, 2015 at 14:04 Joelgullander asked Sep 1, 2015 at 13:22 JoelgullanderJoelgullander 1,6842 gold badges22 silver badges51 bronze badges 11
  • 1 Try /([^ ]*Dog[^ ]*)/ – Lauromine Commented Sep 1, 2015 at 13:25
  • No results at all :/ @Lauromine – Joelgullander Commented Sep 1, 2015 at 13:27
  • @Codehiker post the html please ! – cнŝdk Commented Sep 1, 2015 at 13:47
  • @chsdk Posted html in first post! – Joelgullander Commented Sep 1, 2015 at 14:04
  • p:containsi(" + query + ") must be p:contains(" + query + ") there's an extra i after contains, no? – cнŝdk Commented Sep 1, 2015 at 14:05
 |  Show 6 more ments

4 Answers 4

Reset to default 3

In that case you need to include the whole word in your Regex, try the following one:

(\\b)( \\w*'+ query + '\\w*)(\\b)

And your code will be:

var html = "The Doggy dog is with Doglets and Doggy too!";
var query = "dog";

document.write(html.replace(new RegExp('(\\b)( \\w*' + query + '\\w*)(\\b)', 'ig'), "<span class='search-enlight'>$&</span>"));
.search-enlight {
  background-color: yellow;
  color: red;
}

Could you post a sample of your html before being replaced ? cause /([^ ]Dog[^ ])/ should work, but you seems to have some \b in your string around your keyword so the answer should be

([^ ]*)(\\bdog\\b)([^ ]*)

for a string like

test of \bdog\blet

Use this instead: \b.*?dog.*?\b.

The problem with your expression is that you are attempting to match the query part surrounded by word boundaries. Adding .*? before and after will instruct the regex engine to do a non greedy search for other characters which are between the substring you are interested and the word boundaries:

return html.replace(new RegExp('(\\b)(.*?' + query + '.*?)(\\b)', 'ig'), "<span class='search-enlight'>$&</span>");

Example available here.

Another option:

\w*Dog\w*

Test is here.

发布评论

评论列表(0)

  1. 暂无评论