首页 > 解决方案 > 使用html实体的Javascript替换()不起作用

问题描述

我有以下脚本,它成功地将 < 和 > 替换为下面指示的代码。这里的想法是,如果用户希望“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>'));
});

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

标签: javascripthtml

解决方案


该字符'['不是字符实体,因此未编码。只需将其直接传递给replace

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

推荐阅读