Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use ".replace()" and ".html()" to turn plaintext into an image tag?

I am attempting to modify this answer in order to take classic BCCode [img]{url}[/img] and display an html image from it. As seen in my code snippet, I have been able to successfully do something similar with [b]text[/b]. For some reason, though, with [img][/img] the image doesn't display at all.

So, how can I use .replace() and .html() to turn plaintext into an image tag?

$('#boldText').click(function() {
  $('#bold').html(function(i, htm) {
    return htm.replace(/\[b\]/g, '<b>');
  }); // Replace opening tag
  $('#bold').html(function(i, htm) {
    return htm.replace(/\[\/b\]/g, '</b>');
  }); // Replace closing tag
});
$('#createImage').click(function() {
  $('#image').html(function(i, htm) {
    return htm.replace(/\[img\]/g, '<img src="');
  }); // Replace opening tag
  $('#image').html(function(i, htm) {
    return htm.replace(/\[\/img\]/g, '">');
  }); // Replace closing tag
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="bold">
  [b]bold text[/b]
</p>
<button id="boldText">
  Make above text bold
</button>
<p id="image">
  [img]http://i.imgur.com/mFJlvPf.jpg[/img]
</p>
<button id="createImage">
  Make above text into image
</button>
like image 994
SpyderScript Avatar asked Dec 11 '25 02:12

SpyderScript


1 Answers

Problem of your code is in replacing string to tag in two part. When javascript trying to insert <img src=" or "> into html, browser doesn't insert it because it is invalid tag. Use both of .replace() after string for chain in one .html() function.

$('#boldText').click(function() {
  $('#bold').html(function(i, htm) {
    return htm.replace(/\[b\]/g, '<b>').replace(/\[\/b\]/g, '</b>');
  }); 
});
$('#createImage').click(function() {
  $('#image').html(function(i, htm) {
    return htm.replace(/\[img\]/g, '<img src="').replace(/\[\/img\]/g, '">');
  }); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="bold">
  [b]bold text[/b]
</p>
<button id="boldText">
  Make above text bold
</button>
<p id="image">
  [img]http://i.imgur.com/mFJlvPf.jpg[/img]
</p>
<button id="createImage">
  Make above text into image
</button>
like image 123
Mohammad Avatar answered Dec 13 '25 18:12

Mohammad