ditto
ditto

Reputation: 6277

JS: Extract number from string, that is before a specific word

I want to extract the number that is exactly before the text kcal. How may I do this?

foo = "1119 kJ / 266 kcal";

// want to return: 266

http://regex101.com/r/tZ3fH8/1

Upvotes: 1

Views: 1961

Answers (2)

hwnd
hwnd

Reputation: 70722

You can use a capturing group to match and capture the digits preceding that word. The below regex will match/capture any character of: digits, . "one or more" times preceded by optional whitespace followed by the word "kcal".

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

Upvotes: 3

Victor Stoddard
Victor Stoddard

Reputation: 3721

Regex is simpler and cleaner but if it's not for you then here's another route. You can split your string by the "/" then split it again by the resulting pairs:

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

Upvotes: 0

Related Questions