2

I'm receiving various strings from an api using . I have been stripping the html from these strings as follows:

var comb = $(qu1[i].title + qu1[i].content).text()

I have encountered a problem with strings like this: San Diego Zoo's Animal Bytes:, which returns a syntax error. I'm not sure why jquery is having a problem with this string.

Any idea how I can handle this?

Filburt
  • 17,626
  • 12
  • 64
  • 115
Phil
  • 159
  • 5

1 Answers1

2

Because it is not a selector, and newer versions of jQuery (1.9+) no longer parse html strings that do not start with <. Try:

var comb = $('<div>').append($.parseHTML(qu1[i].title + qu1[i].content)).text();

$.parseHTML is available in jQuery 1.8+ and helps preventing XSS (this does not strip all JS, only script tags. onevent attributes are kept). Though, if the source is trustworthy you can append the html directly. I prefer to be on the safer side. =]

Basically, the code creates an element (div) on the fly and appends the cleanly parsed markup then retrieves its text presentation. I can't claim originality though, similar approaches are shown at How to decode HTML entities using jQuery? and many other threads.

As no references are kept to the div element nor its wrapper jQuery object, these will be collected by the GC very fast.

Reference:

jQuery Core 1.9 Upgrade Guide - jQuery(htmlString) versus jQuery(selectorString)

Community
  • 1
  • 1
Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166