Search code examples
javascripturltemplate-strings

How to flatten a template string in JavaScript


In Javascript I want to flatten my template string. So I want this:

const str = `
    my name
    is
    frank
`

To turn in to this:

const str = 'my name is frank'

The reason why I am asking is because the massive open spaces with `` is causing errors in GET request URLs, for example:

const url = `
    http://0.0.0.0
    :${port}/
    apiCallName?
    var1=${var1}
    var2=${var2}
`

Will turn into something massive like:

const url = '%20%20%20%20%20%20http://0.0.0.0%20%20%20%20%20%20:80/%20%20%20...'

Which breaks the call. I do NOT want to build the string using ' + var1 + '. I find the template strings read much better, so I would like to keep using them.

NOTE: it shouldn't replace all white spaces. Because sometimes I like writing big strings with spaces in them, like:

const str = `
    <label>This is label 1</label>
    <button>This is button 1</button>
`

This should not lose the spaces, so NOT this:

const str = '<label>Thisislabel1</label><button>Thisisbutton1</button>'

Solution

  • You can use replace and it's callback function.

    ([ ]+)|(\n)
    
    • ([ ]+) - Matches space character one or more time. ( g1 )
    • | - Alternation same as logical OR.
    • (\n+) - Matches new line character. ( g2 )

    const str = `
        my name
        is
        frank
    `
    
    const op = str.replace(/([ ]+)|(\n+)/gm,function(match,g1,g2){
      if(g1) return ' '
      else return ''
    })
    
    console.log(op.trim())