Algorithm


  1. Input:

    • Accept a string input.
  2. Initialize a Variable:

    • Initialize a variable to store the result (output) string.
  3. Loop Through Characters:

    • Use a loop to iterate through each character in the input string.
  4. Check for Line Break:

    • Check if the current character is a line break (newline character \n or carriage return character \r).
  5. Replace Line Break:

    • If a line break is found, append the <br> tag to the result string instead of the line break character.
  6. Append Other Characters:

    • If the character is not a line break, append it to the result string as it is.
  7. Output:

    • After processing all characters in the input string, the result string will contain <br> tags in place of line breaks.

 

Code Examples

#1 Code Example- Replace All Line Breaks Using RegEx

Code - Javascript Programming

// program to replace all line breaks in a string with 
const string = `I am Learning JavaScript. JavaScript is fun. JavaScript is easy.`; const result = string.replace(/(\r\n|\r|\n)/g, ' < br>'); console.log(result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
I am Learning JavaScript.
JavaScript is fun.
JavaScript is easy.

#2 Code Example- Replace All Line Breaks Using Built-in Methods

Code - Javascript Programming

// program to replace all line breaks in a string with 
const string = `I am Learning JavaScript. JavaScript is fun. JavaScript is easy.`; const result = string.split('\n').join(' < br>'); console.log(result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
I am Learning JavaScript.
JavaScript is fun.
JavaScript is easy.
Advertisements

Demonstration


JavaScript Programing to Replace All Line Breaks with <br>-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way