17

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.

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
waka-waka-waka
  • 1,025
  • 3
  • 14
  • 30
  • It's JavaScript, so start by finding out what you do and don't need to escape and how to escape it: [Regular Expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) – zero298 Mar 17 '14 at 21:40

2 Answers2

26

You can do this without any modules:

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

Edit:

A shorter version:

str.replace(/[\\$'"]/g, "\\$&")

(Thanks to Mike Samuel from the comments)

technomage
  • 9,861
  • 2
  • 26
  • 40
Dr. McKay
  • 2,727
  • 2
  • 15
  • 19
2

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

Works On Mine
  • 1,111
  • 1
  • 8
  • 20
  • Thanks all! http://stackoverflow.com/questions/3115150/how-to-escape-regular-expression-special-characters-using-javascript seems to be better. – waka-waka-waka Mar 17 '14 at 21:54