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

如何在JavaScript中将指定前缀后的字符串转为驼峰式(camelCase)

如何用JavaScript实现指定前缀后的驼峰式转换?

需求:将带有指定前缀(如user)的字符串转换为驼峰式(camelCase),例如把useracting转为userActing,即前缀后的第一个字母大写。

你提供的原代码存在问题:正则/-./g匹配的是连字符+任意字符,但目标字符串useracting中没有连字符,因此替换逻辑不会触发,最终结果还是原字符串。

正确实现方案

1. 固定前缀场景

如果前缀是固定的(比如始终是user),可以直接通过字符串截取和拼接实现:

const s = "useracting";
const prefix = "user";
let newVal = s;

if (s.startsWith(prefix) && s.length > prefix.length) {
  // 截取前缀后的部分,首字母大写后与前缀拼接
  const suffix = s.slice(prefix.length);
  newVal = prefix + suffix.charAt(0).toUpperCase() + suffix.slice(1);
}

console.log(newVal); // 输出: userActing

2. 通用函数(支持动态指定前缀)

如果需要适配不同前缀,可以封装成通用函数:

function camelCaseWithPrefix(str, prefix) {
  // 校验:字符串不以指定前缀开头,或前缀后无字符,直接返回原字符串
  if (!str.startsWith(prefix) || str.length <= prefix.length) {
    return str;
  }
  
  const suffix = str.slice(prefix.length);
  return prefix + suffix.charAt(0).toUpperCase() + suffix.slice(1);
}

// 使用示例
const testStr = "useracting";
const result = camelCaseWithPrefix(testStr, "user");
console.log(result); // 输出: userActing

逻辑说明

  1. 先校验字符串是否符合条件:必须以指定前缀开头,且前缀后还有剩余字符;
  2. 截取前缀后的子串,将子串的第一个字母转为大写;
  3. 把原前缀、大写后的首字母、剩余子串拼接,得到最终的驼峰式字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 08:28:32