How to transform input value into string

3

How do I make the value of an input into a string, including whether the user types HTML tags, with JavaScript or jQuery.

<div class="val-input" contenteditable="true"></div>

$(function(){
    var val = $(".val-input").text();
});

I want the result to come out like this if the user types an HTML tag (the quotation marks represent the string)

"<p class="teste">Ola mundo!</p>"

And not like this:

Ola mundo!
    
asked by anonymous 23.05.2015 / 01:38

2 answers

3

If I understand your problem well, what you want is to escape the HTML tags so you can see the source code like this:

  

The world!

.

For this you have to transform some of the symbols of this HTML string into their corresponding HTML entities.

I suggest using a library for this eg he.js

The code looks like this:

$(function(){
    var val = $(".val-input").html(); // aqui tem de ser .html()
    var text = he.escape(val);        // <- esta é a linha que queres
    $("#mostrador").html(text);       // aqui tem de ser .html()
});

example: link

Option for simple strings:

If the strings are simple you can use this code :

 var entityMap = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': '&quot;',
    "'": '&#39;',
    "/": '&#x2F;'
  };

  function escapeHtml(string) {
    return String(string).replace(/[&<>"'\/]/g, function (s) {
      return entityMap[s];
    });
  }

What the code does is look in the string for characters like &<>"'\/ and substitute them in the string for its visual representation in HTML, which is in the entityMap object.

Example: link

    
23.05.2015 / 12:08
2

You can use .html() instead of .text() .

In free translation the .html() :

  

Gets the HTML content of the first element in the paired element set or sets the HTML content of each matching element.

Thus

You can use the code below to get content HTML contenteditable

$(function(){
    var val = $(".val-input").html();
});
    
23.05.2015 / 04:13