Created
May 3, 2017 17:21
-
-
Save skoshy/f9f2c326a62b1ec24240c0dcea911163 to your computer and use it in GitHub Desktop.
Cuts a substring from a string based on a leading/trailing string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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