Why has the $ variable in the replacement string passed to replace () been interrupted for some time?

I have a variable that I use to create a JavaScript function call, and JavaScript .replace()to surround a line of text with a span and onclick event. The part is .replace()as follows:

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 libcontains a $at the end of some time; for example lib == DPDRI$. This causes the JavaScript on my page to break, and I get an output that breaks at the end liband displays the rest of the parameters of the Javascript function as plain text:

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

I have been looking for answers for a few days. I tried to do lib.replace(/\$/g, "\\$");, and \$successfully breaks into a variable, but it still breaks my code. It seems that the JavaScript engine is trying to interpret $at the end libas a captured coincidence, and this makes it explode. Anyone have any ideas how to make this work?

+3
source share
1 answer

See Specifying a String as a Parameter Section of the MDC replace()Documentation :

The replacement string may include the following special replacement patterns:

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

: ​​, onclick, '- , $, " :

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

, . , $:

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

"DPDRI $" "DPDRI $$" , $.

+2

Source: https://habr.com/ru/post/1736218/


All Articles