从页面中查找长度为4的文本

Find text of length 4 from page

本文关键字:文本 查找      更新时间:2023-09-26

我想搜索页面上所有长度为4的单词或文本,并将其替换为使用regex 的函数返回的其他文本

$("#changeRandom").click(function() {
      $("body").children().each(function() {
        $(this).text($(this).text().replace(/([a-zA-Z]){4}/g,"hello"));
      });
});

您不需要在这里循环或jQuery,它可以简单地用Js完成。但是,从您的代码中可以明显看出您对jQuery的偏好,您可以通过3个简单的步骤来完成这项工作:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network. Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network.Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network.</p>
<button onclick="replaceFunction()">Replace overflow with exchange</button>
<script>
function replaceFunction() {
  
    var repWith ="exchange";
    var content = $("body").html(); 
    var result = content.replace(/overflow/gi, repWith);
    $("body").html(result);
 
}
</script>