在javascript中从字符串中提取数据的更有效方法?

时间:2017-07-30 17:20:08

标签: javascript node.js

我有来自聊天客户端的消息,我想要解析#符号然后提取1-3位数字加上数字后的字母。由于我不知道数字是1,2或3位长,我将每个测试为整数,然后分配变量。我提出了以下代码,但我的编程技巧非常基础......

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' );
}

是否有一种更有效的方法来编码,因为我觉得它是一种强力方法。

3 个答案:

答案 0 :(得分:3)

var result = test.match(/#(\d{1,3})([a-zA-Z])/);
if (result) {
    var numbers = result[1];
    var character = result[2];
}

这会提取1-3个数字(在#符号后面)后跟一个字符(在az大写的范围内,如果你需要任何特殊字符,例如äüß,你需要将它们添加到两个不同的捕获中)组,然后将这些捕获组读入两个变量。请注意,这只会提取第一个匹配项。

答案 1 :(得分:2)

您可以搜索#并删除数字。

var getNumber = s => (s.match(/#(\d+)/) || [])[1];
    
console.log(getNumber('it doesnt matter how long the message is I only need #222c'));
console.log(getNumber('foo'));
console.log(getNumber('fo2o'));

答案 2 :(得分:0)

var test = 'it doesnt matter how long the message is I only need #222c';
var result=0;
(test.split("#")[1]||"").split("").every(char=>parseInt(char,10)&&(result=result*10+ +char));
console.log(result);

只是一个非正则表达式的答案......