JavaScriptで新しい行を追加する方法


この短いチュートリアルでは、JavaScriptの文字列を処理する際に行ブレークに使用できる複数のメソッドを見ます.
このチュートリアルでは、柔軟に我々のイニシアチブの一部は、しばしば使用される興味深いコンセプトの周りキュレーションチュートリアルを書くことです.

目次
  • What is a new line in Javascript?
  • Breaking string using an Escape sequence
  • New line using Template literals
  • HTML Break Element

  • JavaScriptの新しい行は何ですか?

    Manipulating strings in javascript can be a hassle. Although string manipulation is easy to learn, implementing them is tricky and one similar area is adding new lines. There are many ways in which new lines can be added in javascript however it is not as simple as the paragraph or break tag we use in HTML. Nonetheless, let's look at the most commonly used methods.


    エスケープシーケンスを使用して文字列を破壊する

    Escape sequences are the most commonly used method to create a new line in javascript. The escape sequence used to create a new line in Windows and Linux is \n , but in a few older macs \r is used. The implementation of escape sequences is quite straightforward. I have added a snippet below.

    let flexiple = "Hire the top 1% freelance talent";
    
    let new_flexiple = "Hire the \ntop 1% \nfreelance talent";
    
    console.log(flexiple);
    //Output: "Hire the top 1% freelance talent"
    
    console.log(new_flexiple);
    //Output: "Hire the 
    //top 1% 
    //freelance talent"
    

    Note: Remember not to add spaces after the new line escape sequence as javascript would consider that to be a space and add it to the output as well.


    テンプレートリテラルを使用した新しい行

    Template literals sound quite fancy, but underneath the jargon, they are just string literals that allow embedded expressions. This makes it easy to use multi-line strings. We do not enclose template literals with single or double quotes but rather with backtick ( \ ).

    let flexiple = "Hire the \ntop 1% \nfreelance talent";
    
    let new_flexiple = `Hire the 
    top 1% 
    freelance talent`;
    
    console.log(flexiple);
    //Output: "Hire the 
    //top 1% 
    //freelance talent"
    
    console.log(new_flexiple);
    //Output: "Hire the 
    //top 1% 
    //freelance talent"
    

    In both cases, the same output is returned. but as you can see Template Literals make it quite simple to write multi-line strings.


    ブレーク要素

    Adding HTML line break elements to your string is another method I have seen being used quite often. Though break elements must be used where the division of a line must be significant since this method is quite common we look at it as well.

    <html>
    <body>
    <p id="newline"></p>
    
    <script>
    
    let flexiple = "Hire the" + "<br>" + "top 1% "+ "<br>" + "freelance talent";
    
    document.getElementById("newline").innerHTML = flexiple; 
    
    </script>
    
    </body>
    </html>
    

    Note: Remember to use the .innerHTML and not .innerText as you would with other text content.

    Do let me know your thoughts/ queries in the comment section below.