1

I've got the following script, which successfully replaces < and > with the code indicated below. The idea here is that a user would put into the text box if they want "Bold me" to appear bolded on their blog.

$('.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>'));
});

The problem comes with other html entities. I'm going to simply my example. I want to replace the [ html entity with a paragraph tag, but none of the lines in this script work. I've tried documenting each code that related to the '[' character.

$('.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>'));
});

Any thoughts on this would be greatly appreciated! Thanks!

Rick
  • 4,030
  • 9
  • 24
  • 35
Jason Howard
  • 1,464
  • 1
  • 14
  • 43

1 Answers1

1

The character '[' is not a character entity so it is not encoded. Just pass it directly to replace:

string.replace('[' , '<p>')
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
  • I've just discovered that only the first instance of [ is replaced on the page. Any thoughts as to why? Thanks! – Jason Howard Jul 15 '18 at 11:31
  • @JasonHoward That's how [`String#replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) work. If you want to replace all insantces, you'll have to use a regex with the global modifier `g`: `replace(/\[/g, '

    ')`, or use `split`/`join`.

    – ibrahim mahrir Jul 15 '18 at 11:34
  • Thank you so much! – Jason Howard Jul 15 '18 at 11:38
  • @JasonHoward ... more on that [**here**](https://stackoverflow.com/q/1144783/9867451). And you're welcome! – ibrahim mahrir Jul 15 '18 at 11:39