我想提取刚好在文本kcal
之前的数字。我该怎么做?JS:从字符串中提取数字,即在特定单词之前提取
foo = "1119 kJ/266 kcal";
// want to return: 266
http://regex101.com/r/tZ3fH8/1
我想提取刚好在文本kcal
之前的数字。我该怎么做?JS:从字符串中提取数字,即在特定单词之前提取
foo = "1119 kJ/266 kcal";
// want to return: 266
http://regex101.com/r/tZ3fH8/1
正则表达式更简单,更清洁,但如果它不适合你,那么这里是另一条路线。您可以通过拆分您的字符串“/”,然后再通过所产生的对拆呢:
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);
}
Regexp将会更快更好地完成工作。 – Cheery 2014-11-21 01:00:57
http://regex101.com/r/tZ3fH8/2和JS(因为你选择了正则表达式在PHP的链接) - http://regex101.com/r/tZ3fH8/3 – Cheery 2014-11-21 00:57:59