Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
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>

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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>

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!