简体   繁体   English

替换意外删除的新行

[英]Replace unintended deletion of new lines

I have found a strange behavior with replace and regular expressions that I can not explain. 我发现了我无法解释的带有replace和正则表达式的奇怪行为。 I have a trim function that removes spaces from the start and end of each line of a text: 我有一个修整功能,可以从文本的每一行的开头和结尾删除空格:

function trim(str) {
  return str.replace(/^\s+|\s+$/igm, '');
}

But when the text is multi-lined with \\r\\n instead of \\n It also removes the new lines: 但是,当文本用\\ r \\ n而不是\\ n多行显示时,它还会删除新行:

console.log(trim('A string \n- with several \n- lines'))
// A string\n- with several\n- lines
console.log(trim('A string \r\n- with several \r\n- lines'))
// A string- with several- lines

Someone can tell me if this is expected behavior that I don't understand or just one of the warts of JavaScript? 有人可以告诉我这是否是我不理解的预期行为,或者只是JavaScript的疣之一?

EDIT: I don't need to 'fix' the code, I could do it with split + map + trim: 编辑:我不需要“修复”代码,我可以用split + map + trim来做到这一点:

'A string \r\n- with several \r\n- lines'.split('\r\n').map(x => x.trim()).join('\r\n')

I am just curious about the different behaviour in the two examples. 我只是对两个示例中的不同行为感到好奇。 If I use match instead of replace I get this: 如果我使用match而不是replace,则会得到以下信息:

'A string \r\n- with several \r\n- lines'.match(/^\s+|\s+$/igm)
Array(4) [ " \r", "\n", " \r", "\n" ]
'A string \n- with several \n- lines'.match(/^\s+|\s+$/igm)
Array [ " ", " " ]

WAT? WAT?

Change igm to ig . igm更改为ig The problem is the modifier m (multiple lines). 问题是修饰符m (多行)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM