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 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")
.
Remove all line breaks from a long string of text
How do you enter line breaks with raw_input
? But, once you have a string with some characters in it you want to get rid of, just replace
them.
>>> mystr = raw_input('please enter string: ')
please enter string: hello world, how do i enter line breaks?
>>> # pressing enter didn't work...
...
>>> mystr
'hello world, how do i enter line breaks?'
>>> mystr.replace(' ', '')
'helloworld,howdoienterlinebreaks?'
>>>
In the example above, I replaced all spaces. The string '\n'
represents newlines. And \r
represents carriage returns (if you're on windows, you might be getting these and a second replace
will handle them for you!).
basically:
# you probably want to use a space ' ' to replace `\n`
mystring = mystring.replace('\n', ' ').replace('\r', '')
Note also, that it is a bad idea to call your variable string
, as this shadows the module string
. Another name I'd avoid but would love to use sometimes: file
. For the same reason.
remove all line breaks (enter symbols) from the string using R
You need to strip \r
and \n
to remove carriage returns and new lines.
x <- "foo\nbar\rbaz\r\nquux"
gsub("[\r\n]", "", x)
## [1] "foobarbazquux"
Or
library(stringr)
str_replace_all(x, "[\r\n]" , "")
## [1] "foobarbazquux"
How to remove line breaks (no characters!) from the string?
You should be able to replace it with a preg that removes all newlines and carriage returns. The code is:
preg_replace( "/\r|\n/", "", $yourString );
Even though the \n
characters are not appearing, if you are getting carriage returns there is an invisible character there. The preg replace should grab and fix those.
How to remove line breaks from a string, but only between certain tags?
You can use two regex one to replace new line inside tags and another to remove between tags
<[^>]+>[\s\S]+?<\/[^>]+>
--> to remove new line inside tags
(<\/[^>]+>)\n+(?=<[^>]+>)
--> to remove new line between tags
let str = `<h1>HeadlineOne Do not touch</h1>
<p>This is a test string, please put me on one line.</p>
<p>
some text</p>`
let output = str.replace(/<[^>]+>[\s\S]+?<\/[^>]+>/g, m => m.replace(/\n+/g, ''))
let final = output.replace(/(<\/[^>]+>)\n+(?=<[^>]+>)/g,'$1\n')console.log(final)
Remove new line in javascript code in string
If you do not know in advance whether the "new line" is \r
or \n
(in any combination), easiest is to remove both of them:
str = str.replace(/[\n\r]/g, '');
It does what you ask; you end up with newline
. If you want to replace the new line characters with a single space, use
str = str.replace(/[\n\r]+/g, ' ');
Remove line breaks from start and end of string
Try this:
str = str.replace(/^\s+|\s+$/g, '');
jsFiddle here.
Removing line breaks from string
what about this?
var aString = "This is a string \n\n\n This is the second line of the string\n\n"
// trim the string
aString.trimmingCharacters(in: CharacterSet.newlines)
// replace occurences within the string
while let rangeToReplace = aString.range(of: "\n\n") {
aString.replaceSubrange(rangeToReplace, with: "\n")
}
How to eliminate ALL line breaks in string?
Below is the extension method solving my problem. LineSeparator and ParagraphEnding can be of course defined somewhere else, as static values etc.
public static string RemoveLineEndings(this string value)
{
if(String.IsNullOrEmpty(value))
{
return value;
}
string lineSeparator = ((char) 0x2028).ToString();
string paragraphSeparator = ((char)0x2029).ToString();
return value.Replace("\r\n", string.Empty)
.Replace("\n", string.Empty)
.Replace("\r", string.Empty)
.Replace(lineSeparator, string.Empty)
.Replace(paragraphSeparator, string.Empty);
}
Related Topics
Prevent Execution of Parent Event Handler
What Does a Tilde Do When It Precedes an Expression
How to Use Namespaces with Typescript External Modules
How to Download a File with Angular2 or Greater
Iframe Src Change Event Detection
Document.Createelement("Script") Synchronously
Why Variable Hoisting After Return Works on Some Browsers, and Some Not
Binding Arrow Keys in Js/Jquery
Differencebetween Children and Childnodes in JavaScript
Is JavaScript Supported in an Email Message
How Does JavaScript's Sort() Work
How to Access the First Property of a JavaScript Object
Concrete JavaScript Regular Expression for Accented Characters (Diacritics)
How to Iterate Through Table Rows and Cells in JavaScript
How to Use Jquery for Xml Parsing with Namespaces