从JavaScript中的string中提取数据的更有效的方法?

我有一个来自聊天客户端的消息,我想分析一个#号,然后提取1-3位数字后加上一个字母后面的数字。 由于我不知道如果数字将是1,2或3位数字我testing每个整数,然后分配variables。 我想出了下面的代码,但我的编程技巧是非常基本的…

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

有没有更有效的方式来编码,因为我觉得这是一种powershell方法。

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

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

你可以search#并把数字放在后面。

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

只是一个非正则expression式的答案…