18

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.

1
  • It's JavaScript, so start by finding out what you do and don't need to escape and how to escape it: Regular Expression Commented Mar 17, 2014 at 21:40

3 Answers 3

28

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)

Sign up to request clarification or add additional context in comments.

1 Comment

This can be abbreviated to str.replace(/[\\$'"]/g, "\\$&")
3

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 Comment

Thanks all! stackoverflow.com/questions/3115150/… seems to be better.
1

For that I use NodeJs module "querystring".

For example:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.