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>
  • 相关阅读:
    PHP vscode+XDebug 远程断点调试服务器上的代码
    Wordpress 为用户或角色 role 添加 capabilities(权限)
    Wordpress 后台文章编辑区添加模板选择功能
    CentOS 7 编译安装最新版git
    WordPress 通过文章 URL 获取文章 ID
    Web 安全问题 rel="noopener nofollw"
    Wordpress 通过 post id 获取文章 url
    git放弃修改&放弃增加文件
    Wordpress 作者模板页中的自定义帖子类型分页问题
    PHP 删除 url 中的 query string
  • 原文地址:https://www.cnblogs.com/itliulei/p/10305049.html
Copyright © 2011-2022 走看看