jquery :contains 查找指定字符串元素对象实例 并(批量)替换

http://blog.sina.com.cn/s/blog_8ee552f30101en05.html

https://www.cnblogs.com/linxixinxiang/p/11315615.html

jquery 查找指定字符串元素对象实例:

:contains(text)匹配包含给定文本的元素

HTML 代码:

<div>  John Resig  </div>

 

<div>  George Martin  </div>

 

<div id="showContent">  Malcom John Sinclair  </div>

 

<div>  J. Ohn  </div>

jQuery 代码:

$("div:contains('John')")


//通过Id
$("#showContent:contains('John')").html($("#showContent:contains('John')").html().replace(/John/g, "<img src=\"\" alt=\"\"/>"));

//通过class   可批量替换
$(document).ready(function(){
   $(".intro").filter(":contains('is')").each(function() {
        $(this).html($(this).html().replace("is", "are"));
   }); 
});

 

var a='12,13,14,15';现在想把字符串替换,号为-

jquery中的replace方法:a.replace(",","-");只能替换掉第一个,号。即,结果为12-13,14,15

jquery中是没有对字符串进行replaceAll的方法,通常这个时候,全部替换采用正则表达式的方式替换。如下:

var reg = new RegExp(",","g");//g,表示全部替换。

a.replace(reg,"-");

结果:12-13-14-15

 

------------------

结合以上两篇文章,写成我自己的:

把页面上的 gt; 转成 > 需要反斜杠转义

var reg = new RegExp(" gt\;","g");//g,表示全部替换。
$(".p_coten").filter(":contains('gt\;')").each(function() {
//console.log("contains gt\;!");
$(this).html($(this).html().replace(reg, "\> "));
});

 

posted @ 2020-03-01 20:37  香巴拉  阅读(1124)  评论(0编辑  收藏  举报