Sunday, November 6, 2022

[FIXED] How do I replace the last character of the selected regex?

Issue

I want this string {Rotation:[45f,90f],lvl:10s} to turn into {Rotation:[45,90],lvl:10}.

I've tried this:

const bar = `{Rotation:[45f,90f],lvl:10s}`
const regex = /(\d)\w+/g
console.log(bar.replace(regex, '$&'.substring(0, -1)))

I've also tried to just select the letter at the end using $ but I can't seem to get it right.


Solution

You can use

bar.replace(/(\d+)[a-z]\b/gi, '$1')

See the regex demo. Here,

  • (\d+) - captures one or more digits into Group 1
  • [a-z] - matches any letter
  • \b - at the word boundary, ie. at the end of the word
  • gi - all occurrences, case insensitive

The replacement is Group 1 value, $1.

See the JavaScript demo:

const bar = `{Rotation:[45f,90f],lvl:10s}`
const regex = /(\d+)[a-z]\b/gi
console.log(bar.replace(regex, '$1'))



Answered By - Wiktor Stribiżew
Answer Checked By - Candace Johnson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.