Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
How do I use newline characters in an interpolated string with newlines?

I am having issues adding newline characters into a string that already has newlines.

For example:

const foo = "test\ntest";
const string = `mutation {
   some_field: "${foo}"
}`;

This will be output as:

mutation {
   some_field: "test
test"
}

But I want it to output as:

mutation {
   some_field: "test\ntest"
}

Where the existing white-space/newlines are preserved but you can add a string like "test\ntest" 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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

const foo = "test\\ntest";
const string = `mutation {
   some_field: "${foo}"
}`;

console.log(string)

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to put literal \n in the string by escaping the backslash.

const foo = "test\\ntest";
const string = `mutation {
   some_field: "${foo}"
}`;

console.log(string);

But this seems like it's fraught with danger. You should almost certainly be using JSON, not a template literal.

const foo = "test\ntest";
const string = `mutation ${JSON.stringify({
   some_field: foo
}, null, 4)}`;

console.log(string);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda