針對全文透過JS來做重點標示

在前陣子有個Case是要處理搜尋結果頁的部分,要將搜尋出來的內容利用關鍵字進行Highlight,所以有了下面這個範例,是利用正規表示法+JS進行處理,會無視搜尋關鍵字的大小寫,若要區分大小寫可將第45行中的gi,改為g就好,以下是範例頁面的Code,也可以直接連結到範例頁面試試看。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Highlight Text Sample</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <style>
        .f-red{
            color: red;
            font-weight: bold;
        }
    </style>
</head>
<body>
	<div class="container">
		<div class="row">
			<div class="input-group mb-3">
				<input type="text" id="hightlightText" value="我" class="form-control">
				<div class="input-group-append">
				<button class="btn btn-primary" type="button" id="activeBtn">Button</button>
			</div>
		</div>
		</div>
		<div id="content" class="row"></div>
	</div>
</body>
</html>
var htmlText = "";
$.ajax({
    url: "highLightText.txt",
    async: false,
    success: function(response){
        htmlText = response;
    }
});
$("#content").html(htmlText);

var hightlightText = $("#hightlightText").val();
$.fn.highlight = function(what,spanClass) {
    return this.each(function(){
        var container = this,
            content = container.innerHTML,
            pattern = new RegExp('([<.]*)(' + what + ')([<.]*)','gi'),
            replaceWith = '$1<span ' + ( spanClass ? 'class="' + spanClass + '"' : '' ) + '">$2</span>$3',
            highlighted = content.replace(pattern,replaceWith);
        container.innerHTML = highlighted;
    });
}
$('#content').highlight(hightlightText,'f-red');

$("#activeBtn").click(function(){
    $("#content").html(htmlText);
    var hightlightText = $("#hightlightText").val();
    $('#content').highlight(hightlightText,'f-red');
});
<p>給到王平銀日持風臺色營對合我過友的、造也在乎費靜臺白國:投無心面策一十人力委了可來沒?動區雲溫好面些、味又動高兒可來成的常他告臺布來處本我:界沒乎真不下老關,業實了種童不成他神舉經公黑下方、小利頭適不保講以心感校趣facebook不他到代易上海。一設開物愛研題來一下一國該要、機出又際各內案名相落的沒上年水部求沒山大式理密。房長裡再造級……童面費後務,風一也本名。太一息品的看統配北心他合情分子的經易民告只?</p><p>進安太,狀立?</p><p>文它接。於能病到腦反的題光,異卻道華找重有地北得了,去她定究愛,局自明加汽容看google及兒已的facebook兩:未不乎動常看選的所國半成著坐靈人一本成英一環處教時告即小!後也臺市開半:技月家,展教子、起構的相要從王排,臉外產便上。運自片同合可家小的部方單美哥人頭讀更外前喜民,有不馬的,你風的;心說火來的……全起飛事影。</p><p>拉為三參。體成和正地該名玩公可等Google學素母為收營……時世的回過高布家不生世存故研,為親總手?行眼長藝想海能和門新小認中日每收交金又成Facebook來而出還內界官我告展了戲有了的的?</p><p>由在下代保不著春原還其元上計一中合小,合的難修技空麼母於車當為下大灣的更吸如果中法照日目Facebook評一種父魚,目發體必詩遊完到往她數他來們標民。有西加邊,的已明得國多、的且看花性小下時都葉輪我後?觀復大物則的示的戰品照!失分量認法。而日媽運那麼個,名目石師越慢面我的古望科流身代安次野大的大深為坡打南發入定筆境產飛東資再變新西一滿價由親爭水道不合不性,google去實差來。球寶的了放車早大馬產場到使引是名最少不人經進人聲經光我,活連第,風軍工星費書它出。情會了每記、能時外社班們人第底月草。股本我google也。是不大日生未向心獲投時成到告平一樣爸音裡使上後讀如推其界明國報問小國快,打問盡自;裡物候小的了民品著家爭行全位?這時的足子一可等學讀不其今當前生好年點自星我藝資做精只基家他命方資前能一們?facebook美十本世高月有量用不善大一王毒跑們這們其可理出一樣規加還人和其寶再西因觀文葉態,灣木學定,個一知論參細已車不;但地口不別的務際千信記車南的、在營該科讓,我子機數年原是紅戰動感問象易一人所消登衣以他型新三。童愛早十以民國止最時構空夜包害石識小導開Google足活。都是身也個紙失八模用精想修速情不散靜到了小神幾會比找銷消之:行的結星才山風人地。山情資器產們這還上想明生。</p><p>調活前育她一來資!車各向進方加取而向成:使知過不,賽舉師皮;早而運星傳等之是法死技斯身不放facebook也日綠手上,不還國、紅球色統形不發過青展國,運市包,雜開基民場操造奇證;地的會沒工星人去,我作感影她創書處營器病……期有生寫看果公們工張,什館進因了入麼對體算兒低汽?靜但開目地、好久我期展今視義本:政義相會位例皮,加情地分朋學客助……年認校分存片常一是。</p><p>刻爾全否便,此前大檢生生回電性其供假調神約獎因突自阿的。</p>

實際動手玩看看↓↓

You may also like...

287,298 Responses

  1. Excellent pieces. Keep posting such kind of info on your
    site. Im really impressed by your site.
    Hey there, You have done a fantastic job. I will definitely
    digg it and personally suggest to my friends. I am confident they
    will be benefited from this web site.

  2. Aw, this was an incredibly nice post. Finding the time and actual effort to
    make a very good article… but what can I
    say… I procrastinate a whole lot and don’t seem to get anything done.

  3. Hey there! I could have sworn I’ve been to this blog before but after
    checking through some of the post I realized it’s
    new to me. Anyhow, I’m definitely delighted I found it and I’ll be bookmarking and checking back frequently!

  4. Hey there! Quick question that’s entirely off topic. Do you know
    how to make your site mobile friendly? My website looks weird when browsing from my iphone 4.
    I’m trying to find a theme or plugin that
    might be able to resolve this problem. If you have any suggestions, please share.
    Cheers!

  5. Ahaa, its fastidious dialogue about this post here at this web site, I
    have read all that, so at this time me also commenting at this place.

  6. Great blog here! Also your website loads up fast! What web host are you using?
    Can I get your affiliate link to your host? I wish my web site loaded up as fast
    as yours lol

  7. It’s great that you are getting ideas from this article as well as from our argument made at this place.

  8. Heya i’m for the first time here. I came across this board and I find It truly useful & it helped me out a lot.
    I hope to give something back and aid others like you helped me.

  9. Good post. I learn something new and challenging on sites I stumbleupon everyday.
    It will always be useful to read through articles from other writers and practice a little something from other sites.

  10. Please let me know if you’re looking for a author for your weblog.

    You have some really good posts and I believe I would be a good asset.
    If you ever want to take some of the load off, I’d love to write some material for your blog in exchange for a link back to mine.
    Please send me an email if interested. Many thanks!

  11. Erichycle表示:

    Прошу прощения, это не совсем то, что мне нужно. Есть другие варианты?


    В этом что-то есть и мне кажется это отличная идея. Полностью с Вами соглашусь. товаров дом 24, екатеринбург дом каталог товаров или http://188.17.148.172/forum/profile.php?action=show&member=8655 дом уют товары

  12. It’s a pity you don’t have a donate button! I’d without a doubt
    donate to this brilliant blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account.
    I look forward to new updates and will talk about this blog with my Facebook group.
    Chat soon!

  13. Hi there! I just wish to give you a big thumbs
    up for the great information you’ve got right here on this
    post. I will be returning to your site for more soon.

  14. Whoa! This blog looks exactly like my old one! It’s on a completely different
    topic but it has pretty much the same layout
    and design. Excellent choice of colors!

  15. Erichycle表示:

    По-моему, какой бред((((


    Абсолютно с Вами согласен. В этом что-то есть и мне кажется это отличная идея. Я согласен с Вами. торговый дом детских товаров, бумажный дом товары и http://forum.s-manuals.com/index.php?action=profile;u=25471 товары около дома

  16. This is a great tip particularly to those fresh to the blogosphere.
    Short but very accurate information… Thank you for sharing this
    one. A must read article!

  17. Tommyhon表示:

    https://glucophage.top/# generic metformin price

  18. uttehal表示:

    stromectol online uk In addition to identifying the molecule such spectra also yield information about the molecular structure.

  19. Marvinhow表示:

    [url=https://sildenafil.site/]sildenafil mexico pharmacy[/url]

  20. Its such as you learn my mind! You appear to know so much approximately this, like
    you wrote the ebook in it or something. I feel that you just
    can do with a few % to pressure the message home a bit, but other than that, this is wonderful blog.
    An excellent read. I’ll definitely be back.

  21. WarthunderGax表示:

    Here everything is already there Warthunder!
    Магазин для Вартандер!
    вар тандер купить

  22. Christophersud9表示:

    Guys just made a web-page for me, look at the link:
    http://forum.mountainbikebh.com.br/viewtopic.php?f=9&t=974396
    Tell me your prescriptions. Thank you.

  23. Mijxvu表示:

    sulfasalazine 500 mg uk order calan online buy depakote without prescription

  24. WzdIQNM表示:

    Tangiers Casino offers a $100 welcome bonus for new players, plus a 100% match deposit up to $1,000. For example, if you deposit $100 and then play enough in the casino to earn another $100, Tangiers will give you an extra $200!
    https://www.sunbia.com.au/forum/welcome-to-the-forum/the-best-conditions-in-tangierscasinovip

  25. I am sure this piece of writing has touched all the internet visitors, its
    really really nice article on building up new blog.

  26. Jeremiahkxg4表示:

    Guys just made a web-page for me, look at the link:
    http://diabeteshub.in/phpbb/viewtopic.php?f=3&t=296378
    Tell me your guidances. THX!

  27. Tommyhon表示:

    https://glucophage.top/# metformin tablets in india

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。