2

I am not good in regex, I just want to ask help how can I check in the string if it is ended "\r\n" ?

Thank you in advance.

jemz
  • 4,987
  • 18
  • 62
  • 102
  • Try answer for similar question here: http://stackoverflow.com/questions/280634/endswith-in-javascript - it does not create substrings and has max performance – hal May 06 '15 at 09:32
  • @hal: Performance is unlikely to matter, but if it does, it turns out the simple substr method is fastest on Chrome and roughly the same as the indexOf approach on Firefox and IE11: http://jsperf.com/endswith-stackoverflow/14 (modern browsers are really good string ops). And it's faster across the board when the result is false: http://jsperf.com/endswith-stackoverflow-when-false – T.J. Crowder May 06 '15 at 10:03

1 Answers1

6

You don't need regular expressions for that:

if (str.substr(-2) === "\r\n") {
    // Yes, it does
}

When you pass a negative index into substr, it takes it to mean "from the end of the string". So "1234".substr(-2) gives you "34".

If you needed to use a regular expression, it would be /\r\n$/, e.g.:

if (/\r\n$/.test(str)) {
    // Yes, it does
}

The \r\n are matched literally, and the $ is an "assertion" meaning "the input ends here." So \r\n won't be matched if they aren't at the end.


It's probably worth noting that the next version of JavaScript, ES6, will have an endsWith method on strings, and many JavaScript engines (V8 in Chrome, SpiderMonkey in Firefox) already have it. So you can polyfill it if it's not there:

if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(suffix) {
        return this.substr(-suffix.length) === suffix;
    };
}

...which doesn't disturb anything if it's there but adds it if not, then use it:

if (str.endsWith("\r\n")) {
    // Yes, it does
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875