1

I have an expected response, which could be in any format, but for example:

myfoo={FOO}&mybar={BAR}&mybaz={BAZ}

Then I have the response string:

myfoo=hello&mybar=test&mybaz=yup

So my question is, in JavaScript, how can I use these two strings to create an object containing the values, like so:

{
    FOO : 'hello',
    BAR : 'test',
    BAZ : 'yup'
}

In another example the expected string could be a sentence:

Hello, my name is {NAME} and I am {AGE} years old.

Then the actual response:

Hello, my name is Fred and I am 30 years old.

Which should build:

{
    NAME : 'Fred',
    AGE : '30'
}
Connell
  • 13,925
  • 11
  • 59
  • 92
  • This might help: http://stackoverflow.com/questions/1131630/javascript-jquery-param-inverse-function/1131658#1131658 – techfoobar Nov 28 '12 at 13:48

1 Answers1

1

For those interested in how I solved this, I used the following code:

var TAG_REGEX = /\{[A-Z\_]+\}/g,
    expected = 'myfoo={FOO}&mybar={BAR}&mybaz={BAZ}',
    response = 'myfoo=hello&mybar=test&mybaz=yup';

var lengthDifference = 0;
expected.replace(TAG_REGEX, function (tag, index) {
    var afterAll = expected.substr(index + tag.length),
        afterToNextTag = afterAll.indexOf('{'),
        after = afterToNextTag >= 0 ? afterAll.substr(0, afterToNextTag) : afterAll.substr(0),
        startSubstr = response.substr(index + lengthDifference),
        endIndex = after.length ? startSubstr.indexOf(after) : startSubstr.length,
        value = startSubstr.substr(0, endIndex);

    lengthDifference += value.length - tag.length;

    setTagValue(tag, value, responseDiv);
});
Connell
  • 13,925
  • 11
  • 59
  • 92