fedxc
fedxc

Reputation: 195

How to split a string with letters and numbers into different variables using js?

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

Upvotes: 4

Views: 143

Answers (3)

mohkhan
mohkhan

Reputation: 12305

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.

Upvotes: 0

elclanrs
elclanrs

Reputation: 94101

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} 

Upvotes: 2

Ry-
Ry-

Reputation: 224904

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.

Upvotes: 5

Related Questions