简体   繁体   中英

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

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>

I would split the string by all the new lines \n , then trim the items in the array to remove the spaces then join them again with new lines \n . The filter is to remove the items in the split array that could be empty strings

 let message = ` 1 call Alert time: 6:00:57 PM `; console.log(['', ...message.split('\n').filter(Boolean).map(str => str.trim()), ''].join('\n'));

There are, of course, a infinte ways to get to your solution. To make only the indent of the content disappear you can use the following method with your template strings. This ensures that only the indent created by the template string disappears, but the basic formatting remains intact.

 function trimIndent(strings, ...values) { const result = new Array(strings.length); result[0] = strings[0].replace(/^\n/, ''); const endIndex = strings.length - 1; result[endIndex] = strings[endIndex].replace(/\n$/, ''); var indent = result[0].match(/^\s+/g); result[0] = result[0].replace(/^\s+/, ''); for (let i = 0, m = result.length; i < m; i++) { var input = result[i]?? strings[i]; result[i] = input.replace(new RegExp('\n' + indent, "gm"), '\n'); } return result.flatMap((value, index) => { return value + (index < values.length? values[index]: '') }).join(""); } // example call: var user = { id: 10, name: "Kevin", } if (true) { console.log(trimIndent` <div> <span>ID: ${user.id}</span> <span> Username: ${user.name} </span> </div> `); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM