You could clean it up a little:
function parseSubstring(str, after, until) {
var pos0 = after ? str.indexOf(after) : 0,
posS = pos0 > -1 ? pos0 + after.length : str.length,
posE = until ? str.indexOf(until, posS) : str.length;
if (posE >= posS) {
return str.substring(posS, posE);
}
}
var input = "wlan0: adding default route via 192.168.0.1",
part = parseSubstring(input, "route via ");
// -> "192.168.0.1"
On a general note, don't return false if you don't actually want to return a Boolean value. This is not PHP, returning false to indicate an error is the Wrong Thing. If there is no defined result of a function, don't return one at all.
You could also augment the String prototype.
String.prototype.snip = function(after, until) {
var pos0 = after ? str.indexOf(after) : 0,
posS = pos0 > -1 ? pos0 + after.length : this.length,
posE = until ? this.indexOf(until, posS) : this.length;
if (posE >= posS) {
return this.substring(posS, posE);
}
}
var input = "wlan0: adding default route via 192.168.0.1",
part = input.snip("route via ");
// -> "192.168.0.1"
Note how not passing in the until argument translates to "up to the end of the string". Passing the empty string in the after argument would translate to "from the start".
Is there a better way...you haven't explained overall objective