Search code examples
javascriptecmascript-6template-strings

Split template string on line breaks ignoring literal \n


I have some textual data in multiple lines, stored in an ES6 template string. Any line may contain a literal \n string. Example:

`line1
same\nline2
line3`

I want to split that string into an array of lines, where each line originates from a line of the template string, without splitting at a literal \n within a line. So my expected / wanted result was a JavaScript array looking like this: ["line1", "same\nline2", "line3"].

When looking at the example below, this obviously doesn't happen when simply splitting using a regexp for line breaks (/\n/).

So, is this possible at all? Am I missing / misunderstanding something on how template strings work?

const lines = `line1
same\nline2
line3`.split(/\n/);

document.getElementById('out').textContent = JSON.stringify(lines)
<pre id="out"></pre>


Solution

  • You can use the String.raw tag on your template literal:

    const lines = (String.raw `line1
    same\nline2
    line3`).split(/\n/);
    
    console.log(lines);