[英]jQuery replace multiple occurrences of substring/text
我目前正在尝试在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的替换方法来实现这一点。
$(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
命令代表global,这意味着它适用于所有实例。
干得好 -
这里, /\\(|\\)/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>
正则表达式(分裂和加入)的答案:
$(function() {
var notes = $('.notes');
notes.html(notes.html().split(')(').join(')<br/>('));
});
$(document).ready(function() {
$('.notes').html($('.notes').html().replace(/\)\(/g, '<br />'));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.