Home > Enterprise >  How to replace numbers in string if greater than variable?
How to replace numbers in string if greater than variable?

Time:11-22

I have a strings that always contain 2 numbers and I need to replace those numbers with "> 5" if those numbers are greater than 5.

const str = "SmartWear sklad 15&nbsp;ks<br />Externý sklad 12&nbsp;ks"; 
let limit = 5;

The result should be:

const replaced = "SmartWear sklad > 5&nbsp;ks<br />Externý sklad > 5&nbsp;ks";

I tried this, but that won't actually work if the other number is greater than 5 as well.

for (let stock of stocks) {
    let tooltip = stock.getAttribute("data-original-title") //"SmartWear sklad 15&nbsp;ks<br />Externý sklad 0&nbsp;ks";
    let limit = 5;
    const index = tooltip.search(/[0-9]/);
    const firstNum = tooltip[index];

    if (firstNum > limit) {
        const replaced = tooltip.replace(firstNum, `> ${limit}`)
        stock.setAttribute("data-original-title", replaced)
    }
}

CodePudding user response:

.replace with a callback should do the trick

const str = "SmartWear sklad 15&nbsp;ks test 3<br />Externý sklad 12&nbsp;ks"; 
let limit = 5;

newStr = str.replace(/\d /g, 
    num => Number(num) > limit ? `&gt; ${limit}` : num)

document.write(newStr)

  • Related