-2

I tried multiple ways with splits, substrings to get the value of employeeid below, but is there an effective regex way?

/api/getValue;id=12345;age:25;employeeid=4?test=true&othervalues=test

I want to get the employee id value, which is 4. How can I do that?

halfer
  • 19,824
  • 17
  • 99
  • 186
kobe
  • 15,671
  • 15
  • 64
  • 91
  • Does a regex /employeeid=[0-9]+/ not work? – lxe Oct 02 '15 at 22:59
  • it should be generic enough, i can pass employeeid or age or anything and it should get the value. They are not part of querystring thats the problem – kobe Oct 02 '15 at 23:03
  • See http://stackoverflow.com/questions/27745/getting-parts-of-a-url-regex – Mihai8 Oct 02 '15 at 23:06

1 Answers1

1

You could use a simple regular expression to match on employeeid:

// Extract the employeeid with a RegEx
var employeeid = url.match(/;employeeid=(\d+)/, url)[1];

console.log(employeeid);

>>> 4

Or if you'd like this as a function so that any value can be selected you could use the following:

function getValue(url, name) {
    var m = new RegExp(';' + name + '[=:](\\d+)', 'g').exec(url);
    if (m) {
        return m[1];
    }
    return '';
}

var age = getValue(
    '/api/getValue;id=12345;age:25;employeeid=4?test=true&othervalues=test', 
    'age'
    );

console.log(age);

>>> 25
Anthony Blackshaw
  • 2,549
  • 2
  • 16
  • 20
  • curretly i did this way, but not happy – kobe Oct 02 '15 at 23:41
  • hi @kobe I've updated my answer to include a simple regular expression option specifically for `employeeid` - is that what you were after? – Anthony Blackshaw Oct 02 '15 at 23:46
  • 1
    @kobe if you `did this way, but not happy`, please update your question with **the code you've tried**, with the result you've got and **why** it's not the result you want/expect: `not happy` is definitely not explicit enough imho – pomeh Oct 02 '15 at 23:57
  • @kobe I've also added an example of using a function to extract a specific value - I realise my initial example didn't cater for the `age:25` key/value pair being separated by a `:` not a `=` so I've removed that from my original answer. – Anthony Blackshaw Oct 03 '15 at 00:13