【发布时间】:2017-07-19 14:33:37
【问题描述】:
这段代码可以完美地用一些 html 替换字符串:
$('.active_admin_comment_body').each(function(comment_index){
the_string = $(this).text().replace("#Excitement", "<span style=\"background-color: lightgrey;\">#Excitement</span>");
$(this).html(the_string);
)};
上面代码的问题是它只能替换一个值。我有一个值数组,所以我编写了以下代码来循环遍历数组,然后使用数组中的值修改每个注释:
$('.active_admin_comment_body').each(function(comment_index){
hashtags = ["#Excitement", "#Sad News", "#Moderate"];
comment = $(this);
$.each(hashtags, function(index, value){
new_comment = comment.text().replace(value, "<span style='background-color: lightgrey;'>" + value + "</span>");
comment.html(new_comment);
});
});
第一个代码块 100% 工作。仅当您删除 replace 方法中的 html 时,第二个代码块才有效。如何让第二个代码块工作?
【问题讨论】:
-
如果要替换所有匹配项,请使用
str.replace(/textToReplace/g, 'replaceWith'); -
谢谢,但我不确定我是否理解您的评论。我尝试用
replaceWith切换replace,但没有任何改变。我还查看了replaceWith的文档,这似乎是针对 DOM 元素,而不是特定文本。 -
@Philip7899 这不是@YordanNikolov 所说的。他指出您应该将
"#Excitement"更改为/#Excitement/g或RegExp("#Excitement", "g")。g表示替换所有实例而不是替换第一个然后停止。 -
冒着给出一个混蛋答案的风险,正确的解决方案是放弃你的代码并使用模板引擎。
-
我觉得
comment.text().replace...应该改成comment.html().replace...。看我的回答。
标签: javascript jquery replace html-escape-characters