Replace special html characters with regular ones

I get the code from html (ex: a > b) and want to check it for correctness.

The problem is that when I get innerHTML from an element, then, for example, the character > turns into >

I could solve the problem by simply going through all the special characters html and replacing them with regular characters, but that would be a very long solution.

Is there any js method that converts special html - special. characters in the normal ones? I don't want to reinvent the wheel

Author: CppCat, 2019-09-07

1 answers

JQuery

For a sample, insert this, for example:

$(‘form’).submit(function() {
  var theString = $(‘#string’).val();
  var varTitle = $(&#8216;<textarea></textarea>&#8216;).html(theString).text();
  $(&#8216;#output&#8217;).text(varTitle);
  return false;
});

$('form').submit(function() {
  var theString = $('#string').val();
  var varTitle = $('<textarea />').html(theString).text();
  $('#output').text(varTitle);
  return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
  <fieldset>
    <label for="string">Ввведите сущности</label>
    <input type="text" name="string" id="string" />
  </fieldset>
  <fieldset>
    <input type="submit" value="decode" />
  </fieldset>
</form>

<div id="output"></div>
function unescape(some) {
    return some
         .replace(/&lt;/g, "<")
         .replace(/&gt;/g, ">") 
// и т.д.        
 }

Just js

var decodeEntities = (function() {
  // this prevents any overhead from creating the object each time
  var element = document.createElement('div');

  function decodeHTMLEntities (str) {
    if(str && typeof str === 'string') {
      // strip script/html tags
      str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
      str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
      element.innerHTML = str;
      str = element.textContent;
      element.textContent = '';
    }

    return str;
  }

  return decodeHTMLEntities;
})();
 1
Author: Coder, 2019-09-07 09:48:07