Js add new line to string

In JavaScript, you can add a new line to a string using various methods. Here are a few:

  1. Using the \n character:

    const str = "Hello\nWorld";
    console.log(str); // Output: "Hello
    World"

    The \n character is an escape sequence that represents a new line.

  2. Using the + operator:

    const str = "Hello" + "\n" + "World";
    console.log(str); // Output: "Hello
    World"

    You can concatenate strings using the + operator and add a new line character (\n) in between.

  3. Using the String.prototype.concat() method:

    const str = "Hello".concat("\n", "World");
    console.log(str); // Output: "Hello
    World"

    The concat() method allows you to concatenate strings and add a new line character (\n) in between.

  4. Using template literals:

    const str = `Hello
    World`;
    console.log(str); // Output: "Hello
    World"

    Template literals (introduced in ECMAScript 2015) allow you to embed new lines directly in your string using the backtick character (`).

  5. Using the String.prototype.replace() method:

    const str = "Hello";
    str = str.replace(/\n/g, "<br>");
    console.log(str); // Output: "Hello<br>World"

    The replace() method allows you to replace a pattern (in this case, a new line character) with a new string.

These are just a few ways to add a new line to a string in JavaScript. Choose the method that best fits your use case!