-1

I have following string:

"paramFoo={12}, paramBar={1}, paramFooBar={2713}"

Now, I need to get the values for these 3 params. Is there any way to do that in JavaScript/jQuery and/or AngularJS?

I can only think of:

  1. Search for 'paramFoo={' and remove it from the string.
  2. Get position of first '}'
  3. Get value from chars 0 - (pos from 2.)-1
  4. Remove chars 0 - (pos from 2.) from string
  5. [repeat 1-4 two more times]

Im sure, there must be a cleaner way to do that.

Thank you very much!

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Tream
  • 1,049
  • 2
  • 13
  • 29
  • That doesn't look like standard ..... anything. You probably have to `split(',')` etc. – adeneo Dec 15 '14 at 13:01
  • Yeah, split(",") is a good idea. But how can I get the value inside of {}? It is always a number from 0 too XXXX. split("{") and then split("}")? – Tream Dec 15 '14 at 13:02
  • **Do you need** to know that 12 is the value for paramFOO ? – Royi Namir Dec 15 '14 at 13:04
  • And what did you tried so far? – vaso123 Dec 15 '14 at 13:05
  • Whats the data source? The cleanest way if you have control would be to send JSON and use `JSON.parse`. If you have to use that data format, maybe regex could be the answer. Split string on `,` then rip out word part and rip out numbers (if they're consistently of type Number). Let me know if you need help with the regex. But JSON is your safest bet. – Lex Dec 15 '14 at 13:05

2 Answers2

4

Just use a regex!

str.match(/\d+/g)

will give you an array of [12,1,2714].

If you have something other than numbers, the regex will be more complex.

Scimonster
  • 32,893
  • 9
  • 77
  • 89
  • 2
    where is the connection between 12 to paramFoo ? – Royi Namir Dec 15 '14 at 13:02
  • 1
    @RoyiNamir OP only says he needs the values, not the name of the param it was assigned to. – Rory McCrossan Dec 15 '14 at 13:03
  • 1
    @RoryMcCrossan I dont think the OP knows what he wants to tell you the truth. he's just not clear enough – Royi Namir Dec 15 '14 at 13:04
  • @RoyiNamir That I agree with :) – Rory McCrossan Dec 15 '14 at 13:05
  • That just extracts numbers, any numbers. It works here, but doesn't seem like a very good solution in the long run, but who knows, maybe it's all that's needed ? – adeneo Dec 15 '14 at 13:08
  • Thank you very much for your reply. I tested it, and it works like you described. The only problem is now, that (like royi saided) the key is missing, which is needed, since the order of the parameters could be different in very special cases. – Tream Dec 15 '14 at 13:09
2

I would do something like this:

function parse(s) {
    var re = /^([a-zA-Z]+)=\{([0-9]+)\}(?:\,\s*(.*))?$/, parts, res = {};
    while (s && (parts = re.exec(s))) {
        res[parts[1]] = parseInt(parts[2]);
        s = parts[3];
    }
    return res;
}
Maurice Perry
  • 32,610
  • 9
  • 70
  • 97