Writing ECMAScript 6's proposed .contains
, .startsWith
, and .endsWith
methods using good ole .indexOf
.
'carlos'.contains('car');
// true
'carlos'.indexOf('car') >= 0;
// true
'carlos'.startsWith('car');
// true
'carlos'.indexOf('car') === 0;
// true
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
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: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