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.
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.
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
}