views:

62

answers:

1

I have a variable that I'm using to build a JavaScript function call, and JavaScript's .replace() to surround the line of text with a span and onclick event. The .replace() portion looks like this:

code.replace(/(\d{4}\s+)?(LOCAL|PARAMETER|GLOBAL)\s+USING\s+([\S]+)/g, 
   "<span class=\"natprint_popup\" onclick=\"getNaturalCode('" 
     + lib 
     + "','$3','@#test_prod_qual|',0,'Y'); return false;\">$&</span>");

The only problem is that the variable lib contains a $ at the end some of the time; for example, lib == DPDRI$. This causes the JavaScript on my page to break and I get output that breaks at the end of lib and displays the rest of the Javascript function parameters as plain text:

,'DPDPDRNO','TEST',0,'Y'); return false;">

I've been looking fruitlessly for answers for a few days now. I've tried doing lib.replace(/\$/g, "\\$"); and the \$ is successfully making its way into the variable but it still breaks my code. It seems like the JavaScript engine is trying to interpret the $ at the end of lib as a captured match and it's making it blow up. Anyone have any ideas how to make this work?

+1  A: 

See the Specifying a string as a parameter section of the replace() documentation on MDC:

The replacement string can include the following special replacement patterns:

Pattern    Inserts
$$    Inserts a "$".
...
$'    Inserts the portion of the string that follows the matched substring.
...

Note that since the contents of your variable is being inserted as a single-quote-wrapped parameter to the function you're calling from onclick, it will always be followed by a ' - so when it ends with a $, you'll have inadvertently created a replacement pattern:

 ... onclick=\"getNaturalCode('DPDRI$' ...

Now, you could just change how you quote that particular parameter. But to be safe, you should really escape the $ symbol:

 + lib.replace(/\$/g, "$$$$")

The above modification will convert "DPDRI$" into "DPDRI$$" prior to its insertion into the replacement string, allowing the final replacement to contain a literal $.

Shog9
That seemed to solve my problem. Thanks for the detailed explanation!
chemicles