0

Hey there how do I escape ' and " using javascript regex?

because I want

Annie said, "It's really funny."

to be like,

Annie said, \"It\'s really funny.\"
3
  • 1
    What are you trying to accomplish? Commented Feb 9, 2015 at 2:49
  • I hope the OP isn't trying to escape user input on the client side. Commented Feb 9, 2015 at 3:03
  • no I dont. it's gonna be on the server side. I am working in node. so don't ya woory. Commented Feb 9, 2015 at 3:07

1 Answer 1

1

Use string.replace.

string.replace(/(['"])/g, "\\$1")

Example:

> var s = 'Annie said, "It\'s really funny."'
undefined
> console.log(s.replace(/(['"])/g, "\\$1"))
Annie said, \"It\'s really funny.\"
Sign up to request clarification or add additional context in comments.

3 Comments

you guys are so awesome. @hwnd and avinash-raj I want to ask a question, which is better and more efficient in order to get this done, use 2 replace for ' and " or just use this regex?
@user2558534 use a one.
You the one says, Hey there how do I escape ' and " using javascript regex?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.