从字符串的开始和结束删除分行符

我注意到 trim ()不会从字符串的开头和结尾删除新的行字符,所以我试图用下面的 regex 来实现这一点:

return str.replace(/^\s\n+|\s\n+$/g,'');

这并不能消除新的线条,我担心我在这里超出了我的深度。

剪辑 字符串是用这样的 ejs 生成的

go = ejs.render(data, {
locals: {
format() {
//
}
}
});

就是这样,但前面有几行空白。当我使用 go.trim ()时,我仍然会在前面得到新的行。

<?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>
123607 次浏览

/^\s+|\s+$/g should catch anything. Your current regex may have the problem that if your linebreaks contain \r characters they wouldn't be matched.

Try this:

str = str.replace(/^\s+|\s+$/g, '');

jsFiddle here.

String.trim() does in fact remove newlines (and all other whitespace). Maybe it didn't used to? It definitely does at the time of writing. From the linked documentation (emphasis added):

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).


If you want to trim all newlines plus other potential whitespace, you can use the following:

return str.trim();

If you want to only trim newlines, you can use a solution that targets newlines specifically.

Try this:

str.split('\n').join('');