Is there a way to safely stringify a string to a javascript backquote string?
example:
function stringToDoubleQuote(str: string) {
return JSON.stringify(str)
}
function stringToBackQuote(str: string) {
// ...
}
test:
const quotelist = `- 'singlequote'
- "doublequote"
- `backquote`
- template: ...${0}...${1}...`
console.log('(A)', stringToDoubleQuote(quotelist))
console.log('(B)', stringToBackQuote(quotelist))
expected output:
(A) "- 'singlequote'n- "doublequote"n- `backquote`n- template: ...${0}...${1}..."
(B) `- 'singlequote'
- "doublequote"
- `backquote`
- template: ...${0}...${1}...`
Use case
My goal is to create a module that transforms css files into js files, I want to keep the output file readable and not be a long line full of n, hence the use of backquotes.
for example, this css code:
body {
color: fuchsia;
background: khaki;
}
main{
margin: 2em;
padding: 1em;
}
must not be transformed into this:
const styleElement = document.createElement('style')
document.head.append(style)
styleElement.append( /* css */ "body {n color: fuchsia;n background: khaki;n}nmain{n margin: 2em;n padding: 1em;n}")
but this:
const styleElement = document.createElement('style')
document.head.append(style)
styleElement.append( /* css */ `body {
color: fuchsia;
background: khaki;
}
main{
margin: 2em;
padding: 1em;
}`)
2
Answers
You can use
String.raw
There is no builtin you can use (like
JSON.stringify
), but you can easily build this yourself by escaping`
and${
: