Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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";
like image 633
fedxc Avatar asked Mar 24 '23 05:03

fedxc


2 Answers

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.

like image 98
Ry- Avatar answered Mar 25 '23 19:03

Ry-


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} 
like image 37
elclanrs Avatar answered Mar 25 '23 18:03

elclanrs