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

regex replace last occurance of number in between 2 chars javascript

I am trying to replace the last number of each match in between parenthasees.

so if i had cos(3 * 3)

before this regex

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

result = result.replace(/\d+(?:\.\d+)?/g, x => `${x}deg`)

would turn cos(3 * 3) into cos(3deg * 3deg) I need only the last number to be changed to deg so if I had cos(3 * 3) + cos(3 * 2) it would be cos(3 * 3deg) + cos(3 * 2deg)

what regular expression magic could I use to do this.

>Solution :

You can simply use the closing braces to replace like this:

var result = "cos(3 * 3) + cos(3 * 245)"

result = result.replace(/(\d+)(\))/g,'$1deg)')

console.log(result)

Or just replace the last bracket.

var result = "cos(3 * 90) + sin(3 * 2)"

result = result.replace(/\)/g,'deg)')

console.log(result)

With Decimal add a character class using [] for . and digits

var result = "cos(3 * 3.4) + cos(3 * 245.5)"

result = result.replace(/([\d\.]+)(\))/g,'$1deg)')

console.log(result)
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