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.
我在想,你怎么能避开nodejs中的特殊角色呢?我有一个字符串$what$ever$,我需要它转义成\$what\ ever\$在我调用python脚本之前。
I tired querystring npm package but it does something else.
我厌倦了querystring npm包,但它做了其他事情。
Thanks!
谢谢!
2 个解决方案
#1
10
You can do this without any modules:
无需任何模块即可完成:
str.replace(/\\/g, "\\\\")
.replace(/\$/g, "\\$")
.replace(/'/g, "\\'")
.replace(/"/g, "\\\"");
#2
1
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
另一种选择是使用替换。但是你必须对每个实例调用多次。这将是漫长而麻烦的。这是最简短的代码片段
#1
10
You can do this without any modules:
无需任何模块即可完成:
str.replace(/\\/g, "\\\\")
.replace(/\$/g, "\\$")
.replace(/'/g, "\\'")
.replace(/"/g, "\\\"");
#2
1
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
另一种选择是使用替换。但是你必须对每个实例调用多次。这将是漫长而麻烦的。这是最简短的代码片段