jQuery替换多次出现的子字符串/文本
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的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 />'));
});
相关文章:
- JSON解析字符串文本中的双引号
- 未将字符串文本附加到DOM
- jQuery替换多次出现的子字符串/文本
- 未终止的字符串文本问题
- 以字符串形式内化字符串文本
- MVC - 处理新行的未终止字符串文本
- 如何取消转义 JavaScript 字符串文本值
- 未终止的字符串文本,不换行
- 未终止的字符串文本/无效或意外的令牌
- 当您将字符串文本传递给变量,然后将该字符串中的数据分配给新变量时,它叫什么
- 在Javascript中将字符串文本提取为常量是一种最佳实践吗
- 如何将二进制数据从binaryjs转换为字符串/文本
- 在Javascript字符串文本中解释HTML标记
- Selenium IDE在字符串文本中提供了SyntaxError:JSON.parse:错误的控制字符
- 聚合物元素未在字符串/文本中的聚合物中注册
- 语法错误未终止字符串文本jquery
- 为什么大多数语言在字符串文本中使用双引号而不是单引号
- 如何使用jquery在span中显示多行字符串文本?
- 使用javascript存储动态内容时,未终止字符串文本错误
- 奇怪的未终止字符串文本错误与Firefox