zoukankan      html  css  js  c++  java
  • 正则替换标签内的字符串

    <!DOCTYPE html>
    <html>
    <head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
    .dd{
    color:aquamarine;
    font-size: 20px;
    }
    </style>
    </head>
    <body>
    <div class="dd">★</div>
    <div class="dd">✩</div>

    </body>
    </html>
    <script src="lib/js/jquery-3.1.1.min.js"></script>
    <script>
    //高亮关键字 text =>内容 words:关键词 tag 被包裹的标签
    console.log(highLightKeywords('这是对的吗','这是的啊'));
    console.log(highLightKeyw('这是对的吗','这是'));
    console.log(highlight('这是对的吗','这是'));
    //匹配每一个关键字字符
    function highLightKeywords(text, words, tag) {
    tag = tag || 'span';// 默认的标签,如果没有指定,使用span
    var i, len = words.length, re;
    for (i = 0; i < len; i++) {
    // 正则匹配所有的文本
    re = new RegExp(words[i], 'g');
    console.log(re)
    if (re.test(text)) {
    text = text.replace(re, '<'+ tag +' class="highlight">$&</'+ tag +'>');
    // text = text.replace(re, '<'+ tag +' class="highlight">'+words[i]+'</'+ tag +'>');
    }
    }
    return text;
    }

    function highLightKeyw(text, words, tag) {
    tag = tag || 'span';// 默认的标签,如果没有指定,使用span
    //匹配整个关键词
    re = new RegExp(words, 'g');

    if(re.test(text)) {
    text = text.replace(re, '<' + tag + ' class="highlight">$&</' + tag + '>');
    }
    return text;
    }
     
    //匹配整个关键词 不拆分
    function highlight(text, words, tag) {
    // 默认的标签,如果没有指定,使用span
    tag = tag || 'span';
    var i, len = words.length,
    re;
    //匹配每一个特殊字符 ,进行转义
    var specialStr = ["*", ".", "?", "+", "$", "^", "[", "]", "{", "}", "|", "\", "(", ")", "/", "%"];
    $.each(specialStr, function(i, item) {
    if(words.indexOf(item) != -1) {
    words = words.replace(new RegExp("\" + item, 'g'), "\" + item);
    }
    });
    re = new RegExp(words, 'g');
    if(re.test(text)) {
    text = text.replace(re, '<' + tag + ' class="highlight">$&</' + tag + '>');
    }
    return text;

    }

    </script>
  • 相关阅读:
    二、网络基础
    Ado.net
    LINQ
    C#[抽象类,接口]
    自定义类库,并引用
    c#重点[封装,继承,多肽]
    c#重点[集合类型]异常,数组,集合ArrayList,List<>,hashTable,hashtable泛型(Dictionary)
    c#重点[数据类型,构造方法,变量,变量,运算符,装箱,拆箱]
    .net reflector激活
    sqlsever备份,还原和导入导出方法
  • 原文地址:https://www.cnblogs.com/itliulei/p/10305049.html
Copyright © 2011-2022 走看看