javascriptphphtmlnicedit

How do you make HTML run instead of show html commands from a database?


I am using nicEdit.js and it saves to the database like this:

<div align="center"><i>test</i><br></div><u><br><font size="5"><b>Become part of our team!</b></font><br></u>

From the database I retrieve it as $jobfulldesc.

This will show it correctly:

<?php
function unhtmlentities ($string) {
  $trans_tbl =get_html_translation_table (HTML_ENTITIES );
  $trans_tbl =array_flip ($trans_tbl );
  return strtr ($string ,$trans_tbl );
}
echo unhtmlentities($jobfulldesc); ?>

That just doesn't work if you try to add nicEdit into your javascript:

<script type="text/javascript">
  bkLib.onDomLoaded(function() {
      var myNicEditor = new nicEditor();
      myNicEditor.setPanel('myInstance1');

 });
</script>
<div id="myInstance1"><?php echo unhtmlentities($jobfulldesc); ?></div>

or inside of:

<textarea><?php echo unhtmlentities($jobfulldesc); ?></textarea>

How do you make it be seen without the format of HTML inside of nicEdit from the database?


Solution

  • You can parse the text from HTML using Javascript only:

    function getText(htmlString) {
           const virtual = document.createElement('div');
           virtual.innerHTML = htmlString;
           return virtual.textContent
    }
    

    Assuming htmlString is coming from database and passing to javascript through PHP.

    demo:

    function getText(htmlString) {
           const virtual = document.createElement('div');
           virtual.innerHTML = htmlString;
           return virtual.textContent
    }
    
    const retreivedHtml = `<div align="center"><i>test</i><br></div><u><br><font size="5"><b>Become part of our team!</b></font><br></u>`;
    
    console.log(
       getText(retreivedHtml)
    )
    // inject it in the textarea
    document.querySelector('textarea').value= getText(retreivedHtml)
     <textarea></textarea>