在JavaScript中的单个多行字符串中的换行符之前修剪尾随空格 [英] Trim trailing spaces before newlines in a single multi-line string in JavaScript
问题描述
说我有这个单字符串,这里我用^表示空格()
Say I have this single string, here I denote spaces (" ") with ^
^^quick^^^\n
^brown^^^\n
^^fox^^^^^\n
使用.replace()删除尾随空格的正则表达式是什么?
使用替换(/ \s + $ / g,)
不是很有用,因为只删除了最后一行的空格
狐狸。
What regular expression to use to remove trailing spaces with .replace()?
using replace(/\s+$/g, "")
not really helpful since that only removes the spaces
on the last line with "fox".
通过其他问题我发现替换(/ \s +(?:$ | \ n)/ g,)
匹配右边的部分
,但也删除了新的行字符,但我确实需要它们。
Going through other questions I found that replace(/\s+(?:$|\n)/g,"")
matches the right sections
but also gets rid of the new line characters but I do need them.
所以完美的结果将是:
^^quick\n
^brown\n
^^fox\n
(只删除所有剩余的尾随空格)
(only trailing spaces are removed everything else stays)
推荐答案
添加'm'
多行修饰符。
replace(/\s+$/gm, "")
或者更快......
Or faster still...
replace(/\s\s*$/gm, "")
为什么这会更快?请参阅:更快的JavaScript修剪
Why is this faster? See: Faster JavaScript Trim
附录:上述表达式具有压缩相邻换行符的潜在不良影响。如果这不是所需的行为,则首选以下模式:
Addendum: The above expression has the potentially unwanted effect of compressing adjacent newlines. If this is not the desired behavior then the following pattern is preferred:
replace(/[^\S\r\n]+$/gm, "")
编辑2013-11-17: - 添加了不压缩连续换行符的替代模式。 (感谢dalgard指出这个缺陷。)
Edited 2013-11-17: - Added alternative pattern which does not compress consecutive newlines. (Thanks to dalgard for pointing this deficiency out.)
这篇关于在JavaScript中的单个多行字符串中的换行符之前修剪尾随空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!