Related articles

String.prototype.startsWith

JavaScript polyfill, by , Monday, May 12th, 2014

In this article, I am going to demonstrate a few ways to write a polyfill for the String.prototype.startsWith method, which is part of ECMAScript 6. startsWith checks if a string starts with a given set of characters parsed as a string. If so it returns true else false. The method takes two parameters, one which is optional;

  • searchString; the set of characters to search for in the string the method is called on.
  • position; the position where to start the search. (this parameter is optional)

String.prototype.startsWith with for-loop

This first version is straight forward, using a simple for-loop to iterate over the characters in the string. We can do this, because in JavaScript, strings are array like objects.

  1. if (!String.prototype.startsWith) {
  2. String.prototype.startsWith = function (searchString, position) {
  3. "use strict";
  4. var str = this,
  5. strLen = str.length,
  6. seaLen = searchString.length,
  7. pos = position || 0,
  8. i;
  9. if (seaLen + pos > strLen) {
  10. return false;
  11. }
  12. for (i = 0; i < seaLen; i++) {
  13. if (str.charCodeAt(pos + i) !== searchString.charCodeAt(i)) {
  14. return false;
  15. }
  16. }
  17. return true;
  18. };
  19. }

String.prototype.startsWith using recursion

This recursive version is rather compact, but to the point. We chain a bunch of return statements together to form one logical expression, which works the same way as the lines 10 - 19 in the for-loop version of this polyfill.

  1. if (!String.prototype.startsWith) {
  2. String.prototype.startsWith = function (searchString, position) {
  3. "use strict";
  4. var str = this,
  5. strLen,
  6. seaLen,
  7. pos = position || 0;
  8. strLen = str.length;
  9. seaLen = searchString.length;
  10. return (seaLen + pos > strLen) ? false : (function nextChar(i) {
  11. return (i >= seaLen) || (function () {
  12. return str.charCodeAt(pos + i) !== searchString.charCodeAt(i) ? false : nextChar(i + 1);
  13. }());
  14. }(0));
  15. };
  16. }