简体   繁体   English

JavaScript正则表达式测试多行字符串是否以回车结尾

[英]JavaScript regex to test if multiline string ends with a carriage return

What is the regex to test whether a multiline string ends with a carriage return? 用于测试多行字符串是否以回车结尾的正则表达式是什么?

This is what I have so far but I'm not convinced it would work for all the different types of line endings (Windows, Linux and Mac): 到目前为止,这是我的想法,但我不相信它适用于所有不同类型的行尾(Windows,Linux和Mac):

/[\r\n]$/.test(myMultiLineString)

Please could someone confirm whether this would work or not? 请有人确认这是否行得通吗? If not, please provide the correct approach. 如果没有,请提供正确的方法。

Edit 编辑

Changed regex from /\\r?\\n$/ to /[\\r\\n]$/ (see comments). 将正则表达式从/\\r?\\n$/更改为/[\\r\\n]$/ (请参见注释)。

You are using this regex: 您正在使用此正则表达式:

/[\r\n]$/

Which means there has to be \\n at the end optionally preceded by \\r or <CR> . 这意味着必须在末尾有\\n ,并可选地\\r<CR>

Some editors on earlier version of Mac were using just \\r as line break character hence if text is edited there then above regex will return false. Mac早期版本上的某些编辑器仅将\\r用作换行符,因此,如果在此处编辑文本,则上述正则表达式将返回false。

Hence it is bit more accurate to use this form: 因此,使用这种形式会更准确:

/[\r\n]$/

This will match either \\n or \\r at the end irrespective of what comes before. 不管之前是什么,都将最后匹配\\n\\r

Reference on Mac OS Line ending Mac OS行尾参考

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

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