1

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"

  • 2
    Split on commas first. Then, match. Also if your prefix is always 4 characters, use substring instead of match. – Brad May 15 '13 at 19:12
  • 1
    Does'nt work how exactly, seems to do just as expected in my [Fiddle](http://jsfiddle.net/LrPXf/) ? – adeneo May 15 '13 at 19:16
  • @adeneo `need the match to return an array with values 100,234,334,"ABC"` – Ian May 15 '13 at 19:18
  • for idiocy sake you can go so low as to do this: `location.hash.substr(1).replace(/(^flt_man|,$)/g, '').split(',flt_man')` – Joseph Marikle May 15 '13 at 19:22

3 Answers3

2

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.

Community
  • 1
  • 1
Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
1

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;
}
gillyspy
  • 1,578
  • 8
  • 14
0
// [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;
    }));
Casey Chu
  • 25,069
  • 10
  • 40
  • 59