JavaScript string newline character?

2018-12-31 10:10发布

Is \n the universal newline character sequence in Javascript for all platforms? If not, how do I determine the character for the current environment?

I'm not asking about the HTML newline element (<BR/>). I'm asking about the newline character sequence used within JavaScript strings.

16条回答
萌妹纸的霸气范
2楼-- · 2018-12-31 10:56
printAccountSummary: function()
        {return "Welcome!" + "\n" + "Your balance is currently $1000 and your interest rate is 1%."}
};
console.log(savingsAccount.printAccountSummary()); // method

Prints:

Welcome!
Your balance is currently $1000 and your interest rate is 1%.
查看更多
墨雨无痕
3楼-- · 2018-12-31 10:58

I had the problem of expressing newline with \n or \r\n.
Magically the character \r which is used for carriage return worked for me like a newline.
So in some cases, it is useful to consider \r too.

查看更多
与君花间醉酒
4楼-- · 2018-12-31 11:02

yes use \n, unless you are generating html code, in which you want to use <br />

查看更多
无色无味的生活
5楼-- · 2018-12-31 11:02

I believe it is -- when you are working with JS strings.

If you are generating HTML, though, you will have to use <br /> tags (not \n, as you're not dealing with JS anymore)

查看更多
永恒的永恒
6楼-- · 2018-12-31 11:05

you can use <br/> and the document.write/, document.writeln one.

查看更多
临风纵饮
7楼-- · 2018-12-31 11:06

It might be easiest to just handle all cases of the new line character instead of checking which case then applying it. For example, if you need to replace the newline then do the following:

htmlstring = stringContainingNewLines.replace(/(\r\n|\n|\r)/gm, "<br>");
查看更多
登录 后发表回答