1

I am stuck on trying to escape only part of a string in jquery.

So straight to the example

$("#tbody").append("Hi <escape this> and <not this>");

I know that I can escape it by doing this.

$("#tbody").text("Hi <escape this> and <not this>");

but then the whole string gets escaped and its not just a row but the whole context of the tbody.

then I tried to put it in several appends like this

$("#tbody").append("Hi");
$("#void").text("<escape this>").appendTo("#tbody");
$("#tbody").append("and <not this>");

Now this creates rows for each append and breaks the structure of my entry as it should only by one row.

Kind Regards

2 Answers2

0

You could do something like this...

var textToBody = "Hi " + escape("<escape this>") + " and <not this>";
$("#tbody").append(textToBody);

More Help...

Miguel
  • 1,157
  • 1
  • 15
  • 28
0

You could use HTML Entities as jQuery's append() would not parse them and the browser should display them as text:

$("#tbody").append("Hi &lt;escape this&gt; and <not this>");

Output should be:

Hi <escape this> and

The <not this> is rendered as a HTML tag, thus it will not be shown as text.

mathielo
  • 6,725
  • 7
  • 50
  • 63
  • Yes fair enough, my mistake that I did not complete my Question. The would be data from a user. Thanks – Jaco van Rensburg Feb 14 '14 at 03:49
  • @user2715411 then you can do that with simple replaces (first thing that comes in mind!): `var userData = "Fetch any "; userData = userData.replace(//g, '>');`. – mathielo Feb 14 '14 at 03:52
  • Cool I will do this but isnt there a better way? I feel this is not the best way as the input can be anything so i will have to check for each special character that exist. – Jaco van Rensburg Feb 14 '14 at 11:45
  • You can do a little research yourself for that, but in most cases [the above replace example](http://stackoverflow.com/questions/5499078/fastest-method-to-escape-html-tags-as-html-entities) is used or [jQuery's `.text()`](http://stackoverflow.com/questions/24816/escaping-html-strings-with-jquery) as you tried. – mathielo Feb 14 '14 at 12:13