JavaScript: how to use a regular expression to remove blank lines from a string? [closed]

爱⌒轻易说出口 提交于 2019-11-27 18:42:30

Your pattern seems alright, you just need to include the multiline modifier m, so that ^ and $ match line beginnings and endings as well:

/^\s*\n/gm

Without the m, the anchors only match string-beginnings and endings.

Note that you miss out on Mac line endings (only \r). This would help in that case:

/^\s*[\r\n]/gm

Also note that (in both cases) you don't need to match the optional \r in front of the \n explicitly, because that is taken care of by \s*.

As Dex pointed out in a comment, this will fail to clear the last line if it consists only of spaces (and there is no newline after it). A way to fix that would be to make the actual newline optional but include an end-of-line anchor before it. In this case you do have to match the line ending properly though:

/^\s*$(?:\r\n?|\n)/gm

I believe this will work

searchText.replace(/(^[ \t]*\n)/gm, "")

This should do the trick i think:

var el = document.getElementsByName("nameOfTextBox")[0];
el.value.replace(/(\r\n|\n|\r)/gm, "");

EDIT: Removes three types of line breaks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!