PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 6, 2022

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

 November 06, 2022     javascript, regex, regex-group     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing