Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript quotes inside quotes, string literal issue

I am trying to display text in a javascript tooltip

I keep getting unterminated string literals even though: a) the quotes are being slashed, b) there are no line breaks

The text I am trying to display is:

"No, we can't. This is going to be terrible."

(its a quotation from an individual and I want those quotes to display in the tooltip)

My tooltip function works like this

onMouseOver="Tip('string here')"

After I run the string through my function to clean for javascript

function jschars($str) {
        echo preg_replace("/\r?\n/", "\\n", addslashes($str));
}

It comes out looking like this in HTML:

onMouseOver="Tip('\"No, we can\'t. This is going to be terrible.\"')"

This gives me the error unterminated string literal for the first \ in Tip('\

I'm guessing its because im trying to put quotes directly inside the single quotes, how can I get around this for situations like this? (I have tried htmlspecial chars, such as replacing the " with & quot ; - I still get the error

like image 759
samJL Avatar asked Dec 01 '22 04:12

samJL


1 Answers

It's because you're putting double-quotes inside the value of an XML (or html) element:

<div onMouseOver="Tip('\".......

the back-slash doesn't escape it from the context of xml/html. Technically, you'll need to entity-encode the string (after you javascript-escape it). Something like this:

<div onMouseOver="Tip('\&quot;No, we can\'t. This is going to be terrible.\&quot;')" >

Various browsers may or may not deal with that properly. A much better way to approach it would be to give the element an id (or a class, or some other way for you to select it), then add the mouse over handler from a standalone script.

like image 100
Lee Avatar answered Dec 03 '22 17:12

Lee