4

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";

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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} 

10 Comments

mmm... using replace for something that is not a replace? That falls into the too nasty of a hack for me....
replace for looping matches is common practice in my book... I find the while(assignment) pattern harder to read TBH.
Btw, John Resig has an old (2008) post about this usage of replace ejohn.org/blog/search-and-dont-replace
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… It's the matched substring (s1, a174, k is the first parenthesized expression (s) and v is the second parenthesized expression (1) See jsfiddle.net/2YL3z/3
@JuanMendes: You can have the best of both worlds. You need a gmatch helper using this technique and you're golden. I put a lil' demo here: jsbin.com/iredog/1/edit
|
0

Regex can help you...

var myString = "s1a174o10";
var matches = myString.match(/([a-zA-Z]+)|(\d+)/g) || [];

for(var i = 0; i < matches.length; i+=2){
    window[matches[i]] = matches[i+1];
}

WARNING: s,a,o will be global here. If you want, you can declare an object instead of using window here.

1 Comment

This works for the given string, but minitech's answer is more robust since it will work for strings that aren't exactly of that format, like "24a1b2c3". That's because his RegEx expects a number after a character, where yours assumes it starts with string. See jsfiddle.net/2YL3z/2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.