Skip to content

Instantly share code, notes, and snippets.

@suewonjp
Created June 7, 2016 08:04
Show Gist options
  • Save suewonjp/16d05fe0edb278aa7b7962b315ce2c13 to your computer and use it in GitHub Desktop.
Save suewonjp/16d05fe0edb278aa7b7962b315ce2c13 to your computer and use it in GitHub Desktop.
[JavaScript snippet] string prefix, suffix
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);
}
@suewonjp
Copy link
Author

suewonjp commented Jun 7, 2016

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment