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

Given the following line:

var myString = "s1a174o10"; 

I would like to get the following result:

 var s = 1; var a = 174; var o = 10; 

Each letter of the string corresponds to the next number.

Keep in mind that the string is not static, here is another example:

 var myString = "s1p5a100"; 
+4
source share
3 answers

You can do this with a regex:

 var vars = {}; myString.replace(/(\D+)(\d+)/g, function(_,k,v){ vars[k] = +v }); console.log(vars); //=> {s: 1, a: 174, o: 10} 
+2
source

You can use regex:

 var ITEM = /([az])(\d+)/g; 

Then put each match in 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 .

+5
source

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. If you want, you can declare an object instead of using window here.

0
source

Source: https://habr.com/ru/post/1490818/


All Articles