I have a string and would like to simply replace all of the newlines in it with the string " --linebreak-- "
.
Would it be enough to just write:
string = string.replaceAll("\n", " --linebreak-- ");
I'm confused with the regex part of it. Do I need two slashes for the newline? Is this good enough?
The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.
L. replaceAll( "[^a-zA-Z0-9|^!|
The difference between replace() and replaceAll() method is that the replace() method replaces all the occurrences of old char with new char while replaceAll() method replaces all the occurrences of old string with the new string.
Don't use regex!. You only need a plain-text match to replace "\n"
.
Use replace()
to replace a literal string with another:
string = string.replace("\n", " --linebreak-- ");
Note that replace()
still replaces all occurrences, as does replaceAll()
- the difference is that replaceAll()
uses regex to search.
Use below regex:
s.replaceAll("\\r?\\n", " --linebreak-- ")
There's only really two newlines for UNIX and Windows OS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With