Riku Viitasaari
Riku Viitasaari

Reputation: 13

Javascript regexp match of location.hash

How can i match every variable that comes after the text "flt_man" and before "," in the following hash string?

#flt_man100,flt_man234,flt_man334,flt_manABC,

I tried this but it doesn't work.

var check = location.hash.match(/flt_man([^,]*)/g);

I need the match to return an array with values 100,234,334,"ABC"

Upvotes: 1

Views: 1061

Answers (3)

Casey Chu
Casey Chu

Reputation: 25463

// [100, 234, 334, "ABC"]
console.log(location.hash.substr(1) // Get rid of the '#'
    .split(',')
    .filter(function (param) { // Find the parameters
        return /^flt_man/.test(param);
    })
    .map(function (param) { // Get rid of the prefix
        return param.substr('flt_man'.length);
    })
    .map(function (param) { // Optionally cast them to numbers
        return +param || param;
    }));

Upvotes: 0

gillyspy
gillyspy

Reputation: 1598

Less expensive alternative (not that perf matters much here)

var str = "#flt_man100,flt_man234,flt_man334,flt_manABC,";
var arr = str.replace(/[#]?flt_man/g,'').splitCast(',');
arr.pop();

Fiddle

this uses a couple functions i thought were useful enough to abstract

String.prototype.splitCast = function(S){
    var arr = this.split(S);
    for(var i=0, l=arr.length; i<l; i++){
        var value= arr[i];
           arr[i] = !isNaN(parseInt(value,10)) && (parseFloat(value,10) == parseInt(value,10)) ? parseInt(value) : value;
    }
    return arr;
}

Upvotes: 1

Anirudh Ramanathan
Anirudh Ramanathan

Reputation: 46778

How about this?

var str = "#flt_man100,flt_man234,flt_man334,flt_manABC,";
var regex = /flt_man([^,]*)/g;
var arr = new Array();

var result; 
while(result = regex.exec(str)){
    arr.push(result[1]); //can check if numeric
}
console.log(arr); //arr contains what you need

Link to fiddle

To check if numeric you can use this method, and call parseInt() right afterwards.

Upvotes: 2

Related Questions