0

I want to construct an HTML string before I append it to an element. Here is the string:

var html = '<tr><td data-value="' + someValue + '"></td></tr>';
$(el).append(html);

The value in someValue is 24". There is a " in it.

When the HTML is appended the element is wrong. Apparently appending "24"" makes the element recognize only the "24" and there is one loose " in the end. How can I do this?

I tried to replace:

(someValue.indexOf('"') > 0 ? someValue.replace('"','\"') : someValue)

But still the error persists.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Alvin Stefanus
  • 1,873
  • 2
  • 22
  • 60
  • You could either use jQuery methods to add the value as they will escape it for you, eg `attr()` or `data()`, or you could manually HTML encode it: https://stackoverflow.com/a/1219983/519413 – Rory McCrossan Mar 15 '19 at 08:55
  • Possible duplicate of [Populate an input field with a string that contains a double quote](https://stackoverflow.com/questions/5383520/populate-an-input-field-with-a-string-that-contains-a-double-quote) – mrdeadsven Mar 15 '19 at 09:10

2 Answers2

1

Use DOM methods (or jQuery abstractions of them) instead of trying to mash strings into valid HTML.

var tr = $("<tr />);
var td = $("<td />)
    .attr("data-value', someValue);
tr.append(td);
$(el).append(tr);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Ok so according to Quentin's comment. This works:

(someValue.indexOf('"') > 0 ? someValue.replace('"','&quot;') : someValue)

Thanks!

Alvin Stefanus
  • 1,873
  • 2
  • 22
  • 60