I am having issues adding newline characters into a string that already has newlines.
For example:
JavaScript
x
5
1
const foo = "testntest";
2
const string = `mutation {
3
some_field: "${foo}"
4
}`;
5
This will be output as:
JavaScript
1
5
1
mutation {
2
some_field: "test
3
test"
4
}
5
But I want it to output as:
JavaScript
1
4
1
mutation {
2
some_field: "testntest"
3
}
4
Where the existing white-space/newlines are preserved but you can add a string like "testntest"
inside of it. This current line-breaking is causing syntax errors.
I have tried adding together these strings in various different ways but I can’t figure out how to force n
to remain n
in the field value.
Advertisement
Answer
When you have n in a JavaScript string literal, it represents a newline character, not a backslash followed by n. If you want a backslash followed by n, you have to escape the backslash character with another backslash character. That is, you have to put n in the string literal.
JavaScript
1
6
1
const foo = "test\ntest";
2
const string = `mutation {
3
some_field: "${foo}"
4
}`;
5
6
console.log(string)