jimy
jimy

Reputation: 4908

html_entities in javascript

Here i have a textbox in which user inputs html tags like <h1>hello</h1> then i append that text to a td with

 var text = $('textbox').val();
 $('table').append('<tr><td style="padding:0px 12px;color:black">'+(text)+'</td></tr>');

Now what i want is the text in the td should come text as entered <h1>hello</h1> and not hello with h1 tag

I tried escape and unscape but it didnt helped

Upvotes: 0

Views: 271

Answers (6)

dtbarne
dtbarne

Reputation: 8210

PHPJS is an excellent resource for these sorts of "How can I use this PHP function in Javascript?" questions.

Javascript htmlentities()

Upvotes: 0

Gumbo
Gumbo

Reputation: 655795

Here’s a plain JavaScript function without the jQuery overkill:

function htmlEncode(str) {
    return str.replace(/[<>&"']/g, function($0) { return "&" + {"<":"lt",">":"gt","&":"amp",'"':"quot","'":"#39"}[$0] + ";"; });
}

This looks for any occurrence of <, >, &, ", and ', calls the function that then looks up the matched character and returns the corresponding character reference.

Upvotes: 1

Bruce Aldridge
Bruce Aldridge

Reputation: 2937

if you want html_entities ....

try the phpjs project

https://github.com/kvz/phpjs/blob/master/functions/strings/htmlentities.js

.. it also requires this function though https://github.com/kvz/phpjs/blob/master/functions/strings/get_html_translation_table.js

Upvotes: 0

jimy
jimy

Reputation: 4908

Used encode function from here HTML-encoding lost when attribute read from input field

function htmlEncode(value){
  return $('<div/>').text(value).html();
}

 var text = htmlEncode($('textbox').val());
 $('table').append('<tr><td style="padding:0px 12px;color:black">'+(text)+'</td></tr>');

Upvotes: 2

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146660

You need to set the node value with the val() method:

// Untested
var text = $('textbox').val();
var tr = $('<tr><td style="padding:0px 12px;color:black"></td></tr>');
tr.find("td").val(text);
$('table').append(tr);

Upvotes: 0

Mark
Mark

Reputation: 3271

You could try replacing the < by &lt; and > by &gt;

var text = $('textbox').val();
text = text.replace(/</g,'&lt;').replace(/>/g,'&gt;');
$('table').append('<tr><td style="padding:0px 12px;color:black">'+(text)+'</td></tr>');

You can test it yourself here: http://jsfiddle.net/W7RWA/

Upvotes: 0

Related Questions