How to Replace All Line Breaks in a String With ≪Br /≫ Elements

How do I replace all line breaks in a string with br / elements?

This will turn all returns into HTML

str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');

In case you wonder what ?: means.
It is called a non-capturing group. It means that group of regex within the parentheses won't be saved in memory to be referenced later.
You can check out these threads for more information:

https://stackoverflow.com/a/11530881/5042169
https://stackoverflow.com/a/36524555/5042169

How do I find line breaks and replace with br elements in JavaScript?

I'd cover my bets by handling \r\n (the sequence), and then handling \r and \n through a character class, like this:

text = text.replace(/\r\n/g, '<br />').replace(/[\r\n]/g, '<br />');

The first replace turns the sequence \r\n into <br />. The second replace replaces any \r or \n characters found on their own with the string.

More on regular expressions in JavaScript here.

JavaScript replace \n with br /

You need the /g for global matching

replace(/\n/g, "<br />");

This works for me for \n - see this answer if you might have \r\n

NOTE: The dupe is the most complete answer for any combination of \r\n, \r or \n

var messagetoSend = document.getElementById('x').value.replace(/\n/g, "<br />");

console.log(messagetoSend);
<textarea id="x" rows="9">

Line 1





Line 2









Line 3

</textarea>

Replace all break lines present in pre tag with br tag in javascript

Here is a simple solution

export default (html: string): string => {
if (html.indexOf('<pre>') === -1) return html;
const array = html.split('<pre>');
let finalContent = '';
for (let i = 0; i < array.length; i++) {
if (i === 0) {
finalContent = `${array[0]}<pre>`;
} else {
const secondArray = array[i].split('</pre>');
finalContent = `${finalContent}${secondArray[0]
.replace(/\r\n/g, '<br />')
.replace(/[\r\n]/g, '<br />')}</pre>${secondArray[1]}`;
if (i !== array.length - 1) finalContent = `${finalContent}<pre>`;
}
}
return finalContent;
};

How to remove all line breaks from a string

Line breaks (better: newlines) can be one of Carriage Return (CR, \r, on older Macs), Line Feed (LF, \n, on Unices incl. Linux) or CR followed by LF (\r\n, on WinDOS). (Contrary to another answer, this has nothing to do with character encoding.)

Therefore, the most efficient RegExp literal to match all variants is

/\r?\n|\r/

If you want to match all newlines in a string, use a global match,

/\r?\n|\r/g

respectively. Then proceed with the replace method as suggested in several other answers. (Probably you do not want to remove the newlines, but replace them with other whitespace, for example the space character, so that words remain intact.)

How can I replace newlines/line breaks with spaces in javascript?

You can use the .replace() function:

words = words.replace(/\n/g, " ");

Note that you need the g flag on the regular expression to get replace to replace all the newlines with a space rather than just the first one.

Also, note that you have to assign the result of the .replace() to a variable because it returns a new string. It does not modify the existing string. Strings in Javascript are immutable (they aren't directly modified) so any modification operation on a string like .slice(), .concat(), .replace(), etc... returns a new string.

let words = "a\nb\nc\nd\ne";
console.log("Before:");
console.log(words);
words = words.replace(/\n/g, " ");

console.log("After:");
console.log(words);

Replacing line breaks with br tags in multi-line text nodes not enclosed in tags

So it's a little more complicated than what I said in my comment, but I think something like this might work:

public static void main (String[] args)
{
String text = "text11\n"
+ "text 21<p>tagged text1\n"
+ "tagged text2</p>\n"
+ "text 2";

StringBuilder sb = new StringBuilder("<body>");
sb.append(text);
sb.append("</body>");
Document doc = Jsoup.parseBodyFragment(sb.toString());
Element body = doc.select("body");
List<Node> children = body.childNodes();
StringBuilder sb2 = new StringBuilder();
for(Node n : children) {
if(n instanceof TextNode) {
n.text(n.getWholeText().replace("\n", "<br/>"));
}
sb2.append(n.toString());
}
System.out.println(sb2.toString());
}

Basically get all the Nodes, do a replace on the TextNodes, and put them back together. I'm not 100% sure this will work as-is, since I am not able to test it at the moment. But hopefully it gets the idea across.

What I said in my comment doesn't work because you have to be able to put the child elements back in place between the text. You can't do that if you just use getOwnText().

I haven't used Jsoup much myself, so improvements are welcome if anyone has any.

string replace br / to \n gives double breaks

Let me show you. Your code before replacement:

Top spot!<br />\n<br />\n123456789 123456789 123456789

Your code after replacement:

Top spot!\n\n\n\n123456789 123456789 123456789

As you can see <br /> was correctly replaced with new line.

Try to replace <br /> tags with the new lines first:

$commenttext = str_replace("<br />\n", "\n", $reviewdata['comment']);

jQuery - replace line break br / with new line \n

It's unclear which part of your code is failing, although you'll want to double escape the \n carriage return in your replace pattern:

var text = '[employer]<br />[mm/yyy] - [mm/yyy] - ([number] years1, [number] months)<br /><br />'

text = text.replace(/<br\s*\/?>/gim, "\\n")

alert(text);

How to remove line breaks from a file in Java?

You need to set text to the results of text.replace():

String text = readFileAsString("textfile.txt");
text = text.replace("\n", "").replace("\r", "");

This is necessary because Strings are immutable -- calling replace doesn't change the original String, it returns a new one that's been changed. If you don't assign the result to text, then that new String is lost and garbage collected.

As for getting the newline String for any environment -- that is available by calling System.getProperty("line.separator").



Related Topics



Leave a reply



Submit