You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过正则表达式将含点字符串转换为camelcaps格式?

解决带句点字符串转驼峰命名(camelCase)的问题

嘿,我懂你遇到的困扰了——你想把类似 sender.state 这种带句点的字符串转换成驼峰格式(也就是 senderState),但之前用的 'sender.state'.replace(/\./g, '') 只能删掉句点,没法把句点后的第一个字母转成大写,确实达不到预期效果。

给你一个简单有效的解决方案,利用正则表达式的替换回调函数就能搞定:

// 原始字符串
const originalStr = 'sender.state';
// 转换为驼峰命名
const camelCaseStr = originalStr.replace(/\.(.)/g, (_, char) => char.toUpperCase());

console.log(camelCaseStr); // 输出: 'senderState'

代码解释:

  • 正则表达式 /\.(.)/g:全局匹配所有的句点,并且通过括号 (.) 捕获句点后面的第一个字符。
  • 替换的回调函数中,第二个参数 char 就是我们捕获到的句点后的字符,调用 toUpperCase() 把它转成大写,这样就用大写字母替换掉了「句点+小写字母」的组合,完美实现驼峰格式。

这个方法还支持多个句点的场景哦,比如:

const multiDotStr = 'user.profile.contact.email';
const result = multiDotStr.replace(/\.(.)/g, (_, char) => char.toUpperCase());
console.log(result); // 输出: 'userProfileContactEmail'

如果你的字符串可能存在开头或结尾的句点,还可以先做个预处理去掉它们,比如:

const strWithExtraDots = '.sender.state.';
const cleanedStr = strWithExtraDots.replace(/^\.*|\.*$/g, ''); // 去掉开头和结尾的所有句点
const camelCaseResult = cleanedStr.replace(/\.(.)/g, (_, char) => char.toUpperCase());
console.log(camelCaseResult); // 输出: 'senderState'

内容的提问来源于stack exchange,提问作者3gwebtrain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:46:23