简体   繁体   中英

how to escape characters in nodejs?

I was wondering how would you escape special characters in nodejs. I have a string $what$ever$ and I need it escaped like \\$what\\$ever\\$ before i call a python script with it.

I tried querystring npm package but it does something else.

You can do this without any modules:

str.replace(/\\/g, "\\\\")
   .replace(/\$/g, "\\$")
   .replace(/'/g, "\\'")
   .replace(/"/g, "\\\"");

ok heres a quickie. dont expect it to be the most efficient thing out there but it does the job.

"$what$ever$".split("$").join("\\$")

The other option would be use replace. But then you would have to call it multiple times for each instance. that would be long and cumbersome. this is the shortest snippet that does the trick

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