Created
June 7, 2016 08:04
-
-
Save suewonjp/16d05fe0edb278aa7b7962b315ce2c13 to your computer and use it in GitHub Desktop.
[JavaScript snippet] string prefix, suffix
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
function prefix(str, sep) { | |
// prefix("foo.bar.txt", ".") => foo | |
return str && str.substring(0, str.indexOf(sep)); | |
} | |
function suffix(str, sep, excludeSep) { | |
// suffix("foo.bar.txt", ".") => .txt | |
// suffix("foo.bar.txt", ".", true) => txt | |
return str && str.substring(str.lastIndexOf(sep) + (excludeSep === true ? sep.length : 0)); | |
} | |
function inbetween(str, sep0, sep1) { | |
// inbetween("foo.bar.txt", ".", ".") => bar | |
// inbetween("foo.txt", ".", ".") => null | |
if (!str) | |
return null; | |
var idx = str.indexOf(sep0); | |
if (idx < 0) | |
return null; | |
str = str.substring(idx + sep0.length); | |
idx = str.lastIndexOf(sep1); | |
if (idx < 0) | |
return null; | |
return str.substring(0, idx); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that the input string may need trimming before calling the methods for a safety reason.
For instance, suffix("hello world! ", " ") --- Note a trailing space! --- may return an unexpected output;
But suffix("hello world! ".trim(), " ") won't.