0

I have a Javascript / JQuery problem.

I get unterminated string literal when I use this code:

var newInfo = '<div><span class="testClass"><a title="edit" href="'+link+'">'+oldVal+'</a></span></div>';

If I delete the </div> tag, it works... But I need this. I am totally out of ideas.

Maybe you can help, thanks.

DarkAjax
  • 15,955
  • 11
  • 53
  • 65
rattlex
  • 3
  • 1

2 Answers2

1

Escape your slashes.

var newInfo = '<div><span class="testClass"><a title="edit" href="' + link + '">' + oldVal + '<\/a><\/span><\/div>';

You could also just build your html as actual DOM elements instead of a string (which avoids a lot of pitfalls, including this one).

var div = $('<div />'),
    span = $('<span />').addClass('testClass'),
    a = $('<a />').text(oldVal).attr({
        "href": link,
        "title": "edit"
    }),
    newInfo = div.append(span.append(a));
pete
  • 24,141
  • 4
  • 37
  • 51
  • Thanks, that works just fine too.. But I don't understand why. – rattlex Nov 22 '12 at 14:31
  • @rattlex: `/` can have a special meaning in a lot of JavaScript strings, especially when you're passing it to `innerHTML` or a regex, or if it's in a JSON string. In 'innerHTML`, `/` generally only has a special meaning when immediately preceded by '<', so `` in particular needs to be escaped (`<\/`). See http://stackoverflow.com/questions/6117886/two-part-question-on-javascript-forward-slash, http://www.irt.org/articles/js169/#4.7, or https://www.google.com/search?q=why+escape+forward+slash+in+javascript+string for more details. – pete Nov 22 '12 at 16:01
0

Try to use

var newInfo = '<di'+'v><span class="testClass"><a title="edit" href="'+link+'">'+oldVal+'</a></span></di'+'v>';

Seperating the div tags helped me on a similar problem

t0.
  • 361
  • 2
  • 9