Given the following string:
var myString = "s1a174o10";
I would like to have the following result:
var s = 1;
var a = 174;
var o = 10;
Each letter on the string matches the following number.
Keep in mind that the string is not static, here is another example:
var myString = "s1p5a100";
You could use a regular expression:
var ITEM = /([a-z])(\d+)/g;
Then put each match into an object:
var result = {};
var match;
while(match = ITEM.exec(myString)) {
result[match[1]] = +match[2];
}
Now you can use result.s
, result.a
, and result.o
.
You can do this with regex:
var vars = {};
myString.replace(/(\D+)(\d+)/g, function(_,k,v){ vars[k] = +v });
console.log(vars); //=> {s: 1, a: 174, o: 10}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With