简体   繁体   中英

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):

/[\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).

You are using this regex:

/[\r\n]$/

Which means there has to be \\n at the end optionally preceded by \\r or <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.

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.

Reference on Mac OS Line ending

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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