简体   繁体   English

javascript:将a ='x1y2'转换为x = 1且y = 2?

[英]javascript: convert a='x1y2' into x=1 and y=2?

I have the string x61y78 for example. 我有字符串x61y78例如。 How can I divide it into strings var x=61; 如何将其分为字符串var x = 61; and var y=78; 和var y = 78; using javascript? 用javascript?

I tried using for loops and splits but I got weird results and though there should be an easier way. 我尝试使用for循环和拆分,但我得到了奇怪的结果,虽然应该有一个更简单的方法。

You can simply use a regex : 你可以简单地使用正则表达式:

"x61y78".match(/x(\d+)y(\d+)/)

gives you an array where the second and third element are what you want : 为您提供一个数组,其中第二个和第三个元素是您想要的:

["x61y78", "61", "78"]

You can try the approach below: 您可以尝试以下方法:

<script>
function myFunction()
{
var str="x61y78"; 
var n="var x= "+str.slice(1,str.search("y"));
var n=n+" ; var y= "+str.slice(str.search("y")+1);
alert(n);
}
</script>

Output: var x= 61 ; var y= 78 输出: var x= 61 ; var y= 78 var x= 61 ; var y= 78

Assuming the string will be perfect as shown in the question 假设字符串将是完美的,如问题中所示

function makeVars(str){
    var arr = str.match(/[A-Za-z]|[0-9]+/g);
    // validate the array if needed
    for(var i=0; i<arr.length; i+=2){
        this[arr[i]] = arr[i+1];
    }
}

makeVars("x61y78");
console.log(x);
console.log(y);

makeVars will add properties in the context in which it is invoked. makeVars将在调用它的上下文中添加属性。

var object = {};
makeVars.call(object, "a100b200");
console.log(object.a);
console.log(object.b);

maybe this, also if seems rudimental, works good: 也许这个,如果看起来很简陋,也很有效:

var a='x32,13y89.3';
i = a.split('y');
document.write('x:'+i[0].replace('x','')+' <br> y:'+i[1]);

will print: x:32,13 y:89.3 将打印:x:32,13 y:89.3

Usefull with different notations 有用不同的符号

there is more version without assignmnent to x and y: 还有更多版本没有赋值给x和y:

  "x61y78".match(/([0-9]+)/g);

result array: 结果数组:

['61','78']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM