-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\"'

Ayan
  • 2,300
  • 1
  • 13
  • 28

2 Answers2

1

Use JSON.stringify?

console.log(JSON.stringify('Hello "world"').slice(1, -1));
Hugues M.
  • 19,846
  • 6
  • 37
  • 65
  • Hmm already an answer for that [here](https://stackoverflow.com/a/22837870/6730571), but hey, this one is runnable :) – Hugues M. Jun 08 '17 at 08:57
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.

Arg0n
  • 8,283
  • 2
  • 21
  • 38