Cybercartel
Cybercartel

Reputation: 12592

Why do I have to escape and second $ symbol in my Javascript?

I have an document inline script tag with a javascript function but I need to escape the second $ symbol? Why not escaping the both, i.e. the first and the second?

 $js = "<script>$(function(){\$('#slider').anythingSlider({autoPlay: true, delay: 5000, animationTime: 400, easing: \"easeInOutExpo\"});});</script>";

Upvotes: 0

Views: 65

Answers (3)

lanzz
lanzz

Reputation: 43198

Your second $ character is preceeded by a curly brace {, thus triggers the complex (curly) syntax for variable expansion. Your first $ does not have a curly brace, and is not followed by a valid identifier, thus does not need the backslash.

Upvotes: 1

user1430363
user1430363

Reputation:

The escaping is for the PHP. Since you use double Quotes "...", any $.. terms within will have special meaning for the PHP parser (variable substitution). Actually, you should also escape the first occurence of $ in your string, or switch to a single quote string '...'.

Upvotes: 4

xdazz
xdazz

Reputation: 160933

Because you use " quote string, and php's variable use $, the $ need to escape inside a double quote string, or php parse will think that to be a variable.

Upvotes: 3

Related Questions