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!

3
  • LOL! This is the correct answer. I am not a smart man. Commented Jul 15, 2018 at 11:20
  • Feel free to document this as an answer so I can give you credit. Commented Jul 15, 2018 at 11:20
  • @json done. I've turned the comment into an answer. Commented Jul 15, 2018 at 11:29

1 Answer 1

1

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

string.replace('[' , '<p>')
Sign up to request clarification or add additional context in comments.

4 Comments

I've just discovered that only the first instance of [ is replaced on the page. Any thoughts as to why? Thanks!
@JasonHoward That's how String#replace work. If you want to replace all insantces, you'll have to use a regex with the global modifier g: replace(/\[/g, '<p>'), or use split/join.
Thank you so much!
@JasonHoward ... more on that here. And you're welcome!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.