0

I have a string which I want to encode as a single quoted Javascript string. In other words, I want a function asSingleQuotedString, such that:

> console.log(asSingleQuotedString("Hello \"friend\" it's me."))
'Hello "friend" it\'s me'

I have tried using JSON.stringify(), which works, but gives double quoted strings instead.

Hjulle
  • 2,471
  • 1
  • 22
  • 34
  • If anyone wonders *why* I want to do something like this: It is for extracting data from the memory so it can be hard coded in a Javascript file. I want single quoted strings because the strings contains a lot of double quotes (and hardly any single quotes). – Hjulle Nov 15 '15 at 23:01

1 Answers1

0

This is my current solution. It works by converting to JSON format, unescaping the doublequotes, escaping single quotes and then replacing the outer double quotes with single quotes.

// Changes a double quoted string to a single quoted one
function doubleToSingleQuote(x) {
    return x.replace(/\\"/g, '"').replace(/\'/g, "\\'").replace(/^"|"$/g, "'");
}

// Encodes a string as a single quoted string
function asSingleQuotedString(x) {
    return doubleToSingleQuote(JSON.stringify(x));
}

This method also works for arbitrary data structures, by utilizing this regexp for finding all quoted strings:

// Encodes as JSON and converts double quoted strings to single quoted strings
function withSingleQuotedStrings(x) {
    return JSON.stringify(x).replace(/"(?:[^"\\]|\\.)*"/g, doubleToSingleQuote);
}
Community
  • 1
  • 1
Hjulle
  • 2,471
  • 1
  • 22
  • 34