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 ks<br />Externý sklad 12 ks";
let limit = 5;
The result should be:
const replaced = "SmartWear sklad > 5 ks<br />Externý sklad > 5 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 ks<br />Externý sklad 0 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 ks test 3<br />Externý sklad 12 ks";
let limit = 5;
newStr = str.replace(/\d /g,
num => Number(num) > limit ? `> ${limit}` : num)
document.write(newStr)