Skip to content

Instantly share code, notes, and snippets.

@skoshy
Created May 3, 2017 17:21
Show Gist options
  • Save skoshy/f9f2c326a62b1ec24240c0dcea911163 to your computer and use it in GitHub Desktop.
Save skoshy/f9f2c326a62b1ec24240c0dcea911163 to your computer and use it in GitHub Desktop.
Cuts a substring from a string based on a leading/trailing string
/*
Example - https://codepen.io/skoshy/pen/jmLyRm
leading = string, or blank string '' which signifies first character
trailing, string, or blank string '' which signifies last character
*/
function cutSubstr(string, leading, trailing) {
let substr = '';
// first, let's get the primary index
let index1 = string.indexOf(leading);
if (index1 == -1) {
return false;
} else {
index1 += leading.length;
}
// secondary index
let index2;
if (trailing == '') {
// if given an empty string, just go till the end of the string
index2 = string.length;
} else {
index2 = string.indexOf(trailing, index1);
if (index2 == -1) {
return false;
}
}
return string.substring(index1, index2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment