-1

I am looking for an alternative api in javascript for the StringEscapeUtils in java.

Basically it should be able to convert

input string:

He didn't say, "Stop!"

output string:

He didn't say, \"Stop!\"

Can we do the same using any underscore or any other util functions?

In underscore`s escape api,

var a = '"test"'; _.escape(a)

returns

""test""

But I wanted in the format \"test\"'

2
  • 2
    Check out JSON.stringify Commented Jun 8, 2017 at 8:54
  • So basically all you want to do is replace " with \" ...? Commented Jun 8, 2017 at 8:54

2 Answers 2

1

Use JSON.stringify?

console.log(JSON.stringify('Hello "world"').slice(1, -1));

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

1 Comment

Hmm already an answer for that here, but hey, this one is runnable :)
0

If you just want to replace " with \", you can do this:

var s = "He didn't say, \"Stop!\"";
console.log(s.replace(/"/g, '\\\"'));

If you want to escape other characters too, you can do something like this:

var s = "He didn't say, \"Stop!\"";
console.log(s.replace(/("|'|\\)/g, '\\\$1'));

Both examples are using RegExp replace, just different regular expressions used.

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.