JavaScript string newline character?

后端 未结 15 1924
终归单人心
终归单人心 2020-11-22 08:06

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

相关标签:
15条回答
  • 2020-11-22 08:19

    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");
    
    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2020-11-22 08:24

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

    0 讨论(0)
  • 2020-11-22 08:24

    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.

    0 讨论(0)
  • 2020-11-22 08:27

    Get a line separator for the current browser:

    function getLineSeparator() {
      var textarea = document.createElement("textarea");
      textarea.value = "\n"; 
      return textarea.value;
    }
    
    0 讨论(0)
  • 2020-11-22 08:29

    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>");
    
    0 讨论(0)
提交回复
热议问题