waka-waka-waka
waka-waka-waka

Reputation: 1045

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.

Upvotes: 18

Views: 76043

Answers (3)

Majid Rafei
Majid Rafei

Reputation: 87

For that I use NodeJs module "querystring".

For example:

const scapedFilename = querystring.encode({ filename }).replace('filename=', '');

Upvotes: 0

Dr. McKay
Dr. McKay

Reputation: 2977

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)

Upvotes: 28

Works On Mine
Works On Mine

Reputation: 1121

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

Upvotes: 3

Related Questions