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>
You can use the String.raw
tag on your template literal:
const lines = (String.raw `line1
same\nline2
line3`).split(/\n/);
console.log(lines);
\\n
is treated as a new line and regex will always match it. In your string you can escape \\n
like:
`line1
same\\nline2
line3`
Splitting by \\n
will give now:
["line1", "same\nline2", "line3"]
Beware that now \\n
is just a string, not a new line - but you can map this array and replace it to the real new line.
["line1", "same\nline2", "line3"].map(value => value.replace(/\\n/g, "\n"))
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.