Search code examples
javascripttemplate-literals

Remove indentation, but keep line breaks in template literal


I have the following template literal:

let message = `
    1 call
    Alert time: 6:00:57 PM
    `

I've tried various answers from here on SO but for the API I'm working with, none of those solutions work correctly. Those solutions seem to be causing the line breaks after the opening backtick and the ending backtick to be removed along with the indentation.

Because this is happening the API I'm working with is treating the template literal as a single string with no line breaks.

How can I retain all of the line breaks but remove only the indentation in front of 1 call and Alert time: 6:00:57 PM?

My expected output would be this:


1 call
Alert time: 6:00:57 PM


Solution

  • A regular expression can match space characters at the beginning of the line and replace them with nothing, leaving the newlines alone:

    message.replace(/^ +/gm, '')
    

    Demo:

    let message = `
        1 call
        Alert time: 6:00:57 PM
        `
    document.querySelector('textarea').value = message.replace(/^ +/gm, '');
    <textarea></textarea>