Algorithm
-
Input:
- Accept a string input.
-
Initialize a Variable:
- Initialize a variable to store the result (output) string.
-
Loop Through Characters:
- Use a loop to iterate through each character in the input string.
-
Check for Line Break:
- Check if the current character is a line break (newline character
\n
or carriage return character\r
).
- Check if the current character is a line break (newline character
-
Replace Line Break:
- If a line break is found, append the
<br>
tag to the result string instead of the line break character.
- If a line break is found, append the
-
Append Other Characters:
- If the character is not a line break, append it to the result string as it is.
-
Output:
- After processing all characters in the input string, the result string will contain
<br>
tags in place of line breaks.
- After processing all characters in the input string, the result string will contain
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
I am Learning JavaScript.
JavaScript is fun.
JavaScript is easy.
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
I am Learning JavaScript.
JavaScript is fun.
JavaScript is easy.
JavaScript is fun.
JavaScript is easy.
Demonstration
JavaScript Programing to Replace All Line Breaks with <br>-DevsEnv