How to make number operation in js replace function?

Viewed 81
const detailFontSize = fontSize ? fontSize.replace(/(\d+)/, $1-2) : '';

For example, fontSize is "12pt", and I hope to modify it to "10pt". How to make the number operation in replace function with $1?

Codes above do not work since $1 is not defined. and if I add quotes, it will become to "12-2pt"

2 Answers

You can use a function as a second argument of the .replace() to manipulate matched value:

const fontSize = '12pt';

const detailFontSize = fontSize ? fontSize.replace(/(\d+)/, m => Number(m) - 2) : '';

console.log(detailFontSize)

you can also use a var to store the value like a = /(\d+)/.exec(fontSize) and then chck if a is null, if no then (parseInt(a[0]) - 2) + 'pt'; finally, assign the calculated value to the target

Related