最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: How to print the raw content of a string including carriage returns? - Stack Overflow

programmeradmin1浏览0评论

For example if I have a variable:

const template = `line 1
line 2
line 3`;

I want console.log(template) to print:

line 1\nline 2\nline 3

For example if I have a variable:

const template = `line 1
line 2
line 3`;

I want console.log(template) to print:

line 1\nline 2\nline 3

Share Improve this question edited Jan 14, 2020 at 17:19 Run_Script 2,5582 gold badges18 silver badges31 bronze badges asked Jan 14, 2020 at 17:10 sonrhsonrh 371 silver badge7 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 7

Just stringify it

const template = `line 1
line 2
line 3`;

console.log(JSON.stringify(template))

Wele, sonrh!

You can do it something like this:

const template = `line 1
line 2
line 3`;

console.log(template.replace(/\n/g, `\\n`))

You could replace all '\n' with '\\n'

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
}


const template = `line 1
line 2
line 3`;

console.log(replaceAll(template,'\n', `\\n`));

发布评论

评论列表(0)

  1. 暂无评论