简体   繁体   中英

How to insert a <CR> (Carriage Return) in a Javascript String?

I need to insert a Carriage Return in a String. As far as I know the \\r should do it but here is the problem:

I wrote this in the browser console: 1\\r2 then I get: 12 in return. Now I copy/paste it on Notepad++ https://imgur.com/a/pUW8p

There is a CR and a LF there. How I can add just a CR?

Note that you can replace the LF(\\n) in notepad, save the file and the LFs are gone.

In ES6 with string templates you just introduce the carriage return as written text. Also you can use \\n to mark carriage return in quoted strings.

 const str = `l e`; console.log(str); const str2 = 'l\\ne'; console.log(str2); 

Usually, carriage returns often go like this...

\n

and you can use more than one to go down multiple lines.

It's the equivalent of pressing the enter/return key after you type one line and you want to move to the next one.

For example,

var astring = "This is a \n test";

print(astring);

You would get:

This is a
test

Hope it answers your question,

Alexander B.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM