使用html实体的JavaScript replace()无法正常工作

时间:2018-07-15 11:11:57

标签: javascript html

我有以下脚本,该脚本成功将<和>替换为以下代码。这里的想法是,如果用户希望“ Bold me”在其博客上显示为粗体,则将其放在文本框中。

$('.blogbody').each(function() {
  var string = $(this).html();
  $(this).html(string.replace('&lt;', '<span class="bold">'));
});

$('.blogbody').each(function() {
  var string = $(this).html();
  $(this).html(string.replace('&gt;', '</span>'));
});

问题与其他html实体有关。我将仅以我的例子为例。我想用段落标记替换[html实体,但是此脚本中的所有行均无效。我尝试记录与'['字符相关的每个代码。

$('.blogbody').each(function() {
  var string = $(this).html();
  $(this).html(string.replace('&#x0005B;', '<p>'));
});

$('.blogbody').each(function() {
  var string = $(this).html();
  $(this).html(string.replace('&lbrack;', '<p>'));
});

$('.blogbody').each(function() {
  var string = $(this).html();
  $(this).html(string.replace('&lsqb;', '<p>'));
});

$('.blogbody').each(function() {
  var string = $(this).html();
  $(this).html(string.replace('&lbrack;', '<p>'));
});

任何对此的想法将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:1)

字符'['不是character entity,因此未进行编码。只需将其直接传递到replace

string.replace('[' , '<p>')