Reputation: 1175
I have a scenario where i have strings which have the character '<' in it. An example of this is
<a href='#'>foobar</a> foo <bar
Using the native JavaScript (innerHTML
) as well as jQuery (.html()
), while trying to add it to the DOM, the text after and including < gets stripped off
<a href='#'>foobar</a> foo
I tried escaping the '<' however that escapes the <a>
as well. Anchors are not the only html tag that may be there, so how can i handle in such a way that i can only encode the '<' that are not part of any html entity.
An example of the problem - http://jsfiddle.net/ovbg3p8m/
Please note i get the entire HTML from somewhere else and have to work with that.
Thanks.
Upvotes: 0
Views: 64
Reputation: 526
you have to escape the <
var text = '<a href="#">foobar</a> foo <bar foobar';
Find more here Escape html
Upvotes: 0
Reputation: 57703
Let's say your build your HTML like:
var text = "foo <bar";
var link_text = "foobar";
var html = '<a href="#">' + link_text + '</a>' + text;
$(".node").html(html);
If you escape just text
and link_text
(but not html
) you're good.
The distinction between what is html and what isn't is very important.
In PHP there is the function htmlspecialchars
which replaces &, ", ', <
and >
by their escaped forms: & " ' < >
. This is sufficient to avoid breaking HTML.
Upvotes: 0
Reputation: 136
<
is the escaping you desire for this symbol.
The key is to escape what needs to be escaped and not the tag as that is html you want to preserve.
Upvotes: 0
Reputation: 313
Try using the appropriate entry from the HTML name column here.
Upvotes: 0