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 11:09

A note - when using ExtendScript JavaScript (the Adobe Scripting language used in applications like Photoshop CS3+), the character to use is "\r". "\n" will be interpreted as a font character, and many fonts will thus have a block character instead.

For example (to select a layer named 'Note' and add line feeds after all periods):

var layerText = app.activeDocument.artLayers.getByName('Note').textItem.contents;
layerText = layerText.replace(/\. /g,".\r");
查看更多
看风景的人
3楼-- · 2018-12-31 11:10

You can use `` quotes (wich are below Esc button) with ES6. So you can write something like this:

var text = `fjskdfjslfjsl
skfjslfkjsldfjslfjs
jfsfkjslfsljs`;
查看更多
残风、尘缘若梦
4楼-- · 2018-12-31 11:11

In the response to Nilay above (I cannot comment, not enough reputation):

any one know this type of code for tab key? i am tried "%0D%09" but not working. – Nilay Sep 26 '15 at 13:57

Tab is a single character, so if you try just %09 it should be fine. An example to see the individual character codes:

var output = "";
var s="aaa\tbbb\tccc";
for (var i = 0; i < s.length; i++) {
  output += "i=" + i + " charAt=" + s.charAt(i) + " charCodeAt=" + s.charCodeAt(i) + "\n";
}

console.log(output);

查看更多
无与为乐者.
5楼-- · 2018-12-31 11:11

The \n is just fine for all cases I've encountered. I you are working with web, use \n and don't worry about it (unless you have had any newline-related issues).

查看更多
登录 后发表回答