javascript - test if string has postfix (suffix)

JavaScript
[Edit]
+
0
-
0

JavaScript - test if string has postfix (suffix)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
const hasPostfix = (text, prefix) => { if (prefix.length > text.length) { return false; } for (let i = prefix.length - 1, j = text.length - 1; i >= 0; --i, --j) { if (text[j] !== prefix[i]) { return false; } } return true; }; // Usage example: const text = 'This is example text.'; console.log(hasPostfix(text, '')); // true console.log(hasPostfix(text, 'text.')); // true console.log(hasPostfix(text, 'example text.')); // true console.log(hasPostfix(text, '123')); // false console.log(hasPostfix(text, ' ')); // false
Reset
[Edit]
+
0
-
0

JavaScript - test if string has postfix (suffix)

1 2 3 4 5 6 7 8 9 10 11
// Note: ES6 (ES2015) introduced String endsWith() method that lets to check if string starts with prefix. const text = 'This is example text.'; console.log(text.endsWith('')); // true console.log(text.endsWith('text.')); // true console.log(text.endsWith('example text.')); // true console.log(text.endsWith('123')); // false console.log(text.endsWith(' ')); // false
Reset