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

前端:如何为JSON返回的驼峰字符串添加空格并格式化显示

解决驼峰式字符串转带空格的句子格式问题

你当前的toSentenceCase函数仅处理了首字母大写和其余字符小写,但未处理驼峰式字符串中大写字母前添加空格的逻辑,因此无法得到预期的带空格格式。

修改后的字符串处理函数

通过正则表达式匹配驼峰式中的大写字母,在其前插入空格,再统一调整大小写即可实现需求:

const toSentenceCase = (str: string) => {
  // 在每个大写字母前插入空格(跳过字符串首字符)
  const spacedStr = str.replace(/([A-Z])/g, ' $1');
  // 首字母大写,其余转小写,同时去除可能的开头空格
  return spacedStr.charAt(0).toUpperCase() + spacedStr.slice(1).toLowerCase().trim();
};

完整组件代码示例

将上述函数替换原有的toSentenceCase即可:

const toSentenceCase = (str: string) => {
  const spacedStr = str.replace(/([A-Z])/g, ' $1');
  return spacedStr.charAt(0).toUpperCase() + spacedStr.slice(1).toLowerCase().trim();
}

return (
    <div className='fv-row mb-10'>
      <label className='form-label fs-6 fw-bolder text-dark d-flex'>Intent type</label>
      <Form.Select
        aria-label='Select htmlInputTypes'
        className='form-control form-control-lg form-control-solid'
        value={newIntentType}
        onChange={handleTypeChange}
      >
        {defaultJson.map((item, index) => (
          <>
            <option value='' disabled selected hidden>
              Select a Intent Type
            </option>
            <option key={index} value={item.type}>
              {toSentenceCase(item.type)}
            </option>
          </>
        ))}
      </Form.Select>
    </div>
);

效果验证

输入textWithImage时,函数会先转换为text With Image,再调整为Text with image,完全符合你的预期格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 16:03:29