如何替换所选正则表达式的最后一个字符?
我希望这个字符串 {Rotation:[45f,90f],lvl:10s}
变成 {Rotation:[45,90],lvl:10}
。
我已经尝试过:
const bar = `{Rotation:[45f,90f],lvl:10s}`
const regex = /(\d)\w+/g
console.log(bar.replace(regex, '$&'.substring(0, -1)))
我也尝试过使用 $
选择末尾的字母,但我似乎无法正确选择。
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, 'amp;'.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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
查看正则表达式演示。
此处,
(\d+)
- 将一个或多个数字捕获到第 1 组中[az]
- 匹配\b
, IE。位于单词gi
末尾替换为第 1 组值,
$1
。请参阅 JavaScript 演示:
You can use
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 wordgi
- all occurrences, case insensitiveThe replacement is Group 1 value,
$1
.See the JavaScript demo:
检查一下:
Check this out :
您可以使用正向先行来匹配右大括号,但不捕获它。然后可以用空白字符串替换单个字符。
You can use positive lookahead to match the closing brace, but not capture it. Then the single character can be replaced with a blank string.
以下正则表达式将匹配每组一个或多个数字,后跟
f
或s
。$1
表示捕获组(\d)
捕获的内容。The following regex will match each group of one or more digits followed by
f
ors
.$1
represents the contents captured by the capture group(\d)
.