如何替换所选正则表达式的最后一个字符?

发布于 2025-01-15 20:53:31 字数 317 浏览 3 评论 0原文

我希望这个字符串 {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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

浅语花开 2025-01-22 20:53:31

您可以使用

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

查看正则表达式演示
此处,

  • (\d+) - 将一个或多个数字捕获到第 1 组中
  • [az] - 匹配
  • 单词边界处的任何字母 \b , IE。位于单词 gi 末尾
  • - 所有出现的情况,不区分大小写。

替换为第 1 组值,$1

请参阅 JavaScript 演示:

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

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'))

同展鸳鸯锦 2025-01-22 20:53:31

检查一下:

const str = `{Rotation:[45f,90f],lvl:10s}`.split('');
const x = str.splice(str.length - 2, 1)
console.log(str.join(''));

Check this out :

const str = `{Rotation:[45f,90f],lvl:10s}`.split('');
const x = str.splice(str.length - 2, 1)
console.log(str.join(''));
空气里的味道 2025-01-22 20:53:31

您可以使用正向先行来匹配右大括号,但不捕获它。然后可以用空白字符串替换单个字符。

const bar= '{Rotation:[45f,90f],lvl:10s}'
const regex = /.(?=})/g
console.log(bar.replace(regex, ''))
{Rotation:[45f,90f],lvl:10}

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.

const bar= '{Rotation:[45f,90f],lvl:10s}'
const regex = /.(?=})/g
console.log(bar.replace(regex, ''))
{Rotation:[45f,90f],lvl:10}
血之狂魔 2025-01-22 20:53:31

以下正则表达式将匹配每组一个或多个数字,后跟 fs

$1 表示捕获组(\d)捕获的内容。

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

The following regex will match each group of one or more digits followed by f or s.

$1 represents the contents captured by the capture group (\d).

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文