What’s the best way to extract the key and value from a string like this:
var myString = 'A1234=B1234';
I originally had something like this:
myString.split('=');
And that works fine, BUT an equal (=) sign could be used as a key or value within the string plus the string could have quotes, like this:
var myString = ''A123=1=2=3=4'='B1234'';
The string could also only have one pair of quotes and spaces:
var myString = ' 'A123=1=2=3=4' = B1234 ';
I’m not very good at regular expressions but I’m guessing that’s the way forward?
What I want to end up with is two variables, key and value, in the case above, the key variable would end up being A123=1=2=3=4 and the value variable would be B1234.
If there is no value present, for example if this were the original string:
var myString = 'A1234';
Then I would want the key variable to be ‘A1234’ and for the value variable to be null or false – or something I can test against.
Any help is appreciated.
What I’ve tended to do in config files is ensure that there’s no possibility that the separator character can get into either the key or value.
Sometimes that’s easy if you can just say ‘no ‘=’ characters allowed’ but I’ve had to resort to encoding those characters in some places.
I generally hex them up so that if you wanted a ‘=’ character, you would have to put in %3d (and %25 for the ‘%’ character so you don’t think it’s a hex-starter character). You can also use %xx for any character but it’s only required for those two.
That way you can check the line to ensure it has one and only one ‘=’ character then post-process the key and value to turn the hex’ed characters back into real ones.