2014-11-21 94 views

回答

2

您可以使用capturing组匹配和捕获单词前面的数字。下面的正则表达式匹配/捕获任何字符:数字,.“一个或多个”时间前面有可选空白,后跟单词“kcal”。

var r = '1119 kJ/266 kcal'.match(/([\d.]+) *kcal/)[1]; 
if (r) 
    console.log(r); //=> "266" 
+0

将点包含到捕获组中。 – Cheery 2014-11-21 01:01:58

0

正则表达式更简单,更清洁,但如果它不适合你,那么这里是另一条路线。您可以通过拆分您的字符串“/”,然后再通过所产生的对拆呢:

foo = "1119 kJ/266 kcal"; 

pairs = foo.split("/"); 
res = pairs[1]; //get second pair 

var res = foo.split(" "); //spit pair by space. 

if (isNumber(res[0]) { 
    alert("It's a number!"); 
} 

function isNumber(n) { 
    //must test for both conditions 
    return !isNaN(parseFloat(n)) && isFinite(n); 
} 
+0

Regexp将会更快更好地完成工作。 – Cheery 2014-11-21 01:00:57