0

我有一个返回以下内容的 POST AJAX 命令:

`email{admin@stackoverflow.com} cid{215}`

我想要做的是将 email{} 和 cid{} 替换为仅使用值作为 vars

var email = 'admin@stackoverflow.com'
var customer_id = 215;

他们会像那样出现。有没有比以下更清洁的方法:

var result = "email{admin@stackoverflow.com} cid{215}"; 

// change to        admin@stackoverflow.com cid{215}
var replace1 = result.replace("email{");
var replace1a = replace1.replace("}");

// change to        admin@stackoverflow.com 215
var replace2 = result.replace("cid{");
var replace2a = replace1.replace("}");

// now we have an email, with a space and a number
// admin@stackoverflow.com 215 make before space string
// this would be email

// now make only the int a string called cid
4

1 回答 1

2

首先使用正则表达式提取所需数据:

var response = "email{admin@stackoverflow.com} cid{215}";
var regex = /email\{(.*)\} cid\{(.*)\}/;
var data = response.match(regex);

现在您可以轻松获得所需的值:

var email = data[1];
var customer_id = +data[2];
于 2012-06-05T11:55:02.953 回答