skip to Main Content

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


  1. You can use String.raw

    function stringToDoubleQuote(str) {
      return JSON.stringify(str)
    }
    
    function stringToBackQuote(str) {
      return String.raw({ raw: str })
    }
    
    console.log('(A)', stringToDoubleQuote('I don't say:n - "Yes"'))
    console.log('(B)', stringToBackQuote('I don't say:n - "Yes"'))
    Login or Signup to reply.
  2. There is no builtin you can use (like JSON.stringify), but you can easily build this yourself by escaping ` and ${:

    function stringToBackQuote(str: string): string {
      return '`' + str.replace(/`|${/g, '\$&') + '`';
    }
    
    const stringToDoubleQuote = JSON.stringify;
    function stringToBackQuote(str) {
      return '`' + str.replace(/`|${/g, '\$&') + '`';
    }
    const quotelist = `- 'singlequote'
    - "doublequote"
    - `backquote`
    - template: ...${0}...${1}...`
    console.log('(A)', stringToDoubleQuote(quotelist))
    console.log('(B)', stringToBackQuote(quotelist))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search