jQuery替换多次出现的子字符串/文本

jQuery replace multiple occurrences of substring/text

本文关键字:字符串 文本 替换 jQuery      更新时间:2023-09-26

我目前正尝试在jQuery中学习replace方法。

我有一个<div class="notes">,上面有以下文本

  (1 1 1 0 0 1 1)(1 1 1 0 0 1 1)(1 1 1 0 0 1 1)(1 1 1 0 0 0 0)(1 1 1 0 0 1 1)

并且希望用某些值替换文本。例如,每次我看到)(时,我都希望它转到一个新行(<br/>)。我试图使用jQuery的replace方法来实现这一点。

 $(document).ready(function() {
    var text = $('.notes').html().replace(")(", "<br/>");
    $('.notes').html(text);
  });

我注意到,在这样做的时候,它只是取代了第一个实例。所以我尝试了replaceAll方法,尽管这对字符串没有影响。

快速小提琴演示或下面的片段:

$(document).ready(function() {
    var text = $('.notes').html().replace(")(", "<br/>");
    $('.notes').html(text);
    alert(text);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="notes">
  (1 1 1 0 0 1 1)(1 1 1 0 0 1 1)(1 1 1 0 0 1 1)(1 1 1 0 0 0 0)(1 1 1 0 0 1 1)
</div>

有人能建议我该怎么做吗?

您需要使用全局运行的正则表达式,请注意/g命令。

对于您的情况,您需要使用以下内容:

/')'(/g

$(document).ready(function() {
    var text = $('.notes').html().replace(/')'(/g, "<br/>");
    $('.notes').html(text);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="notes">
  (1 1 1 0 0 1 1)(1 1 1 0 0 1 1)(1 1 1 0 0 1 1)(1 1 1 0 0 0 0)(1 1 1 0 0 1 1)
</div>

.replace()是一个String方法,而不是jQuery方法,因此应该使用一个简单的RegExp。

 var text = $('.notes').html().replace(/')'(/g, "<br/>");

请注意代表全局的g命令,这意味着它适用于所有实例。

给你-

这里,/'(|')/g是正则表达式。标志g表示全局。它会导致所有匹配项都被替换。

$(document).ready(function() {
    var text = $('.notes').text().replace(/'(|')/g, "<br/>");
    $('.notes').html(text);
    alert(text);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="notes">
  (1 1 1 0 0 1 1)(1 1 1 0 0 1 1)(1 1 1 0 0 1 1)(1 1 1 0 0 0 0)(1 1 1 0 0 1 1)
</div>

一个带有regex(拆分和联接)的答案:

$(function() {
    var notes = $('.notes');
    notes.html(notes.html().split(')(').join(')<br/>('));
});
$(document).ready(function() {
  $('.notes').html($('.notes').html().replace(/')'(/g, '<br />'));
});