简体   繁体   中英

Javascript str.replace with dollar sign not working

Sample string being replaced:

https://fw.adsafeprotected.com/rjss/bs.serving-sys.com/52023/7720220/BurstingPipe/adServer.bs?cn=rsb&c=28&pli=1234567890&PluID=0&w=300&h=600&ord=[timestamp]&ucm=true&ncu=$${CLICK_URL_ENC}$&adsafe_preview=${IS_PREVIEW}`

Replacements I'm trying to make:

$${CLICK_URL_ENC}$  --> $$${CLICK_URL_ENC}$$
[timestamp]         --> ${CACHEBUSTER}

Desired output:

https://fw.adsafeprotected.com/rjss/bs.serving-sys.com/52023/7720220/BurstingPipe/adServer.bs?cn=rsb&c=28&pli=1234567890&PluID=0&w=300&h=600&ord=${CACHEBUSTER}&ucm=true&ncu=$$${CLICK_URL_ENC}$$&adsafe_preview=${IS_PREVIEW}

Code I've tried:

Code:

var v = $("textarea#creative-content").val();
v = v.replace(/\$\$\{CLICK\_URL\_ENC\}\$/g, "$$${CLICK_URL_ENC}$$");
v = v.replace("[timestamp]","${CACHEBUSTER}");
console.log(v);

Output:

  • Changed [timestamp] to ${CACHEBUSTER} : Yes
  • Changed $${CLICK_URL_ENC}$ to $$${CLICK_URL_ENC}$$ : No

Code:

var v = $("textarea#creative-content").val();
v = v.replace("$${CLICK_URL_ENC}$", "$$${CLICK_URL_ENC}$$");
v = v.replace("[timestamp]","${CACHEBUSTER}");
console.log(v);

Output:

  • Changed [timestamp] to ${CACHEBUSTER} : Yes
  • Changed $${CLICK_URL_ENC}$ to $$${CLICK_URL_ENC}$$ : No

Code:

var v = $("textarea#creative-content").val();
v = v.replace("\$\${CLICK_URL_ENC}\$", "\$\$\${CLICK_URL_ENC}\$\$");
v = v.replace("[timestamp]","${CACHEBUSTER}");
console.log(v);

Output:

  • Changed [timestamp] to ${CACHEBUSTER} : Yes
  • Changed $${CLICK_URL_ENC}$ to $$${CLICK_URL_ENC}$$ : No

How can I make the changes I'm looking for using JavaScript/jQuery?

You need to escape the dollar signs. This is done by typing two in a row. You want to have 3 dollar signs in the beginning, which means you have to have 6 dollar signs in the replace string:

v.replace("$${CLICK_URL_ENC}$", "$$$$$${CLICK_URL_ENC}$$$$");

在替换中,$是捕获组时使用的特殊字符,因此需要使用$符号对其进行转义,这使我们难以理解,例如:

'$${CLICK_URL_ENC}$'.replace(/\$\${CLICK_URL_ENC}\$/g, '$$$$${CLICK_URL_ENC}$$$');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM