how to escape characters in nodejs?

前端 未结 2 450
感动是毒
感动是毒 2021-01-11 10:46

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 wit

相关标签:
2条回答
  • 2021-01-11 11:07

    You can do this without any modules:

    str.replace(/\\/g, "\\\\")
       .replace(/\$/g, "\\$")
       .replace(/'/g, "\\'")
       .replace(/"/g, "\\\"");
    
    0 讨论(0)
  • 2021-01-11 11:24

    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

    0 讨论(0)
提交回复
热议问题