我从一个聊天客户端传来消息,我想解析一个#号,然后提取1-3位数字后加上数字后面的一个字母。由于我不知道这个数字是否是1,2或3位数字,我将每个数字都测试为一个整数,然后分配这些变量。我想出了下面的代码,但我的编程技巧是非常基本的...从JavaScript中的字符串中提取数据的更有效方法?
var test = 'it doesnt matter how long the message is I only need #222c';
var QuID = '';
var Qans = '';
var regInteger = /^\d+$/;
//this function checks to see if a charactor is an integer
function isInteger(str) {
return regInteger.test(str);
}
var IDloc = test.indexOf('#') + 1;
var IDloc2 = test.indexOf('#') + 2
console.log(IDloc);
//This is a brute force method to test if there is a 1-3 digit number and assigning the question number and question answer into variables. Sloppy but it's duct tape and wire programming my friend!
if(isInteger(test.substring(IDloc, IDloc2))) {
QuID = (test.substring(IDloc, IDloc2));
Qans = (test.substring((IDloc + 1), (IDloc2 + 1)));
if (isInteger(test.substring((IDloc +1), (IDloc2 + 1)))) {
QuID = (test.substring(IDloc, (IDloc2 + 1)));
Qans = (test.substring((IDloc + 2), (IDloc2+ 3)));
if (isInteger(test.substring((IDloc + 2), (IDloc2 + 2)))) {
QuID = (test.substring(IDloc, (IDloc2 + 2)));
Qans = (test.substring((IDloc + 3), (IDloc2 + 4)));
}
}
console.log(QuID);
console.log(Qans);
} else {
console.log('Non Integer');
}
有没有,因为我觉得这是一个强力的方法来编写这更有效的方式。
使用您的正则表达式使用组匹配提取值。 – Dai