[英]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";
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
. 现在您可以使用
result.s
, result.a
和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}
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. 警告:s,a,o将在这里全球化。 If you want, you can declare an object instead of using
window
here. 如果需要,可以在此处声明对象而不是使用
window
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.