Reputation: 338
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"
Upvotes: 2
Views: 101
Reputation: 1006
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)
Upvotes: 3
Reputation: 319
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
Upvotes: 0