2
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 2

3

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.