Skip to content

Instantly share code, notes, and snippets.

@cgcardona
Last active December 14, 2015 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgcardona/5018788 to your computer and use it in GitHub Desktop.
Save cgcardona/5018788 to your computer and use it in GitHub Desktop.

Summary

Writing ECMAScript 6's proposed .contains, .startsWith, and .endsWith methods using good ole .indexOf.

.contains

'carlos'.contains('car');
// true
'carlos'.indexOf('car') >= 0;
// true

.startsWith

'carlos'.startsWith('car');
// true
'carlos'.indexOf('car') === 0;
// true

.endsWith

This one looks a little dirty to me because I needed to know the fname and arg in advance. Is there a way to do it so that I don't need those two variables?

'carlos'.endsWith('los');
// true
var fname = 'carlos';
var arg = 'los';
fname.indexOf(arg) == fname.length - arg.length;
// true
@OscarGodson
Copy link

Yeah, it looks a little hacky, but that's because it's not wrapped up. You'd probably make this a function, or more likely, extend String since you know this is a standard. You'd of course check for this but the code would look more like:

String.prototype.endsWith = function (suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

I took a look at the es6-shim too, but my god, why so much code?!

https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L81-L118

@cgcardona
Copy link
Author

:+1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment