Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 603
waka-waka-waka Avatar asked Mar 17 '14 21:03

waka-waka-waka


1 Answers

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)

like image 169
Dr. McKay Avatar answered Sep 21 '22 07:09

Dr. McKay