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

如何用正则表达式将div内每行首字母转换为大写?

修正代码实现每行首字母大写

你的核心问题是正则表达式写法错误,且对String.replace方法的使用逻辑有误。以下是修正后的完整方案:

修正后的JavaScript代码

$('button').on('click', function(){
  let str = $('#wrap').text();
  // 匹配字符串开头或换行后的小写字母,将其转为大写
  let result = str.replace(/(^|\n)([a-z])/g, (match, prefix, char) => prefix + char.toUpperCase());
  $('#wrap').text(result);
});

代码说明

  • 正则表达式/(^|\n)([a-z])/g:
    • (^|\n):捕获字符串开头或换行符,保留原有换行结构
    • ([a-z]):捕获需要转换的小写字母
    • g:全局匹配标记,确保所有符合条件的字符都被处理
  • 替换回调函数:保留捕获到的前缀(开头或换行符),将小写字母转为大写后拼接,保证格式不变

完整可运行代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
.wrap{white-space:pre-wrap;}
</style>
<div class='wrap' id='wrap'>
lorem ipsum
dolor sit

amet
</div>
<button>CLICK</button>
<script>
$('button').on('click', function(){
  let str = $('#wrap').text();
  let result = str.replace(/(^|\n)([a-z])/g, (match, prefix, char) => prefix + char.toUpperCase());
  $('#wrap').text(result);
});
</script>

点击按钮后,文本会转换为:

Lorem ipsum
Dolor sit

Amet

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:55:42