I noticed that trim() does not remove new line characters from the start and end of a string, so I am trying to accomplish this with the following regex:
return str.replace(/^\s\n+|\s\n+$/g,'');
This does not remove the new lines, and I fear I am out of my depth here.
EDIT The string is being generated with ejs like so
go = ejs.render(data, { locals: { format() { // } } });
And this is what go is, but with a few empty lines before. When I use go.trim() I still get the new lines before.
<?xml version="1.0"?> <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format"> <fo:layout-master-set> <fo:simple-page-master master-name="Out" page-width="8.5in" page-height="11in" margin-top="1in" margin-bottom="0.5in" margin-left="0.75in" margin-right="0.75in"> <fo:region-body margin-top="1in" margin-bottom="0.25in"/> <fo:region-before extent="1in"/> <fo:region-after extent="0.25in"/> <fo:region-start extent="0in"/> <fo:region-end extent="0in"/> </fo:simple-page-master> </fo:layout-master-set> <fo:page-sequence master-reference="Out" initial-page-number="1" force-page-count="no-force"> <fo:static-content flow-name="xsl-region-before"> <fo:block font-size="14pt" text-align="center">ONLINE APPLICATION FOR SUMMARY ADVICE</fo:block> <fo:block font-size="13pt" font-weight="bold" text-align="center">Re: SDF, SDF </fo:block> </fo:static-content> <fo:flow flow-name="xsl-region-body" font="10pt Helvetica"> .. removed this content </fo:flow> </fo:page-sequence> </fo:root>
Use the String. replace() method to remove all line breaks from a string, e.g. str. replace(/[\r\n]/gm, ''); . The replace() method will remove all line breaks from the string by replacing them with an empty string.
String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.
The strip() method will remove both trailing and leading newlines from the string. It also removes any whitespaces on both sides of a string. If the newline is at the end of the string, you could use the rstrip() method to remove a trailing newline characters from a string, as shown below.
You can use trim() method if the string contains usual white space characters – space, tabs, newline, a carriage return. The recommended method is strip() to remove all the leading and trailing white space characters from the string.
Try this:
str = str.replace(/^\s+|\s+$/g, '');
jsFiddle here.
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