Skip to content

Instantly share code, notes, and snippets.

@jaymecd

jaymecd/substr.js

Last active May 12, 2019
Embed
What would you like to do?
ES6 training
const substr = (str, start = 0, length = str.length) => {
if (start === 0 && length === str.length) {
return str;
}
if (start > str.length || length <= 0) {
return '';
}
const startIndex = (start < 0) ? Math.max(0, str.length - Math.abs(start)) : start;
const stopIndex = Math.min(str.length, startIndex + length);
let result = '';
for (let i = startIndex; i < stopIndex; i++) {
result += str[i];
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.