Reputation: 2677
I want to parse a string from inside another string, based on a start and end string pattern.
The example is parsing an ip address, however this could be any string, and not necessarily an IP.
Is there a better / more efficient way of doing this:
function parse(str,start,end){
var ls = str.indexOf(start);
if(str && ls !== -1) return str.substring(ls+start.length,str.indexOf(end,ls));
return false;
}
var res = "wlan0: adding default route via 192.168.0.1";
console.log(parse(res,"route via ","\n"));
192.168.0.1
Upvotes: 0
Views: 188
Reputation: 2020
You could consider using regular expressions. This could be a generic beginning (take a look here for a proper RegExp.escape
method):
function parse(str, start, end) {
var start_expr = RegExp.escape(start);
var end_expr = RegExp.escape(end);
var regex = new RegExp( start_expr + "(.*)(?=" + end_expr + ")" );
var match = str.match(regex);
return match[1];
}
You may have to adjust it for your needs, as regex might not directly accept some escape sequences you are used to (e.g. "\n" in your example).
Upvotes: 1
Reputation: 338416
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".
Upvotes: 1