Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace numbers in string if greater than variable?

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";

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

.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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading