DoArNa
DoArNa

Reputation: 532

Extracting data from a string jquery

I have e scenario like this: I need to build a jQuery function that takes a string as an input and update the string into another string. The input can be one of these:

I want the function to updated to:

Option four can have more than two digits after "0, ".

It seems like this can be done by regex somehow but I am not being able to put anything together that can make it work. Any help is appreciated.

Upvotes: 0

Views: 130

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386868

You could split the string and take the last value. If zero return '--'.

function getValue(a) {
    return (+a.split(', ').pop() || '--').toString();
}
 
console.log(getValue("0"));     // "--"
console.log(getValue("0, 5"));  // "5"
console.log(getValue("0, 58")); // "58"
console.log(getValue("58"));    // "58"

A proposal with a regular expression searching for last numbers

function getValue(a) {
    return (+a.match(/\d+$/) || '--').toString();
}
 
console.log(getValue("0"));     // "--"
console.log(getValue("0, 5"));  // "5"
console.log(getValue("0, 58")); // "58"
console.log(getValue("58"));    // "58"

Upvotes: 1

Related Questions