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

如何在JavaScript/AngularJS中将句子首词转换为大写字母

JavaScript/AngularJS 实现句子首单词大写

JavaScript 实现方式

方法一:基础字符串操作

通过字符串方法截取首字符转大写,拼接剩余部分,同时处理空输入避免报错:

function capitalizeFirstWord(str) {
  if (!str) return str;
  return str.charAt(0).toUpperCase() + str.slice(1);
}

// 使用示例
const testSentence = "hello world";
console.log(capitalizeFirstWord(testSentence)); // 输出:Hello world

方法二:正则表达式替换

利用正则匹配字符串开头的第一个单词字符,替换为大写形式:

function capitalizeFirstWord(str) {
  return str.replace(/^\w/, char => char.toUpperCase());
}

// 使用示例
const anotherSentence = "this is a test";
console.log(capitalizeFirstWord(anotherSentence)); // 输出:This is a test

AngularJS 实现方式

在AngularJS中推荐自定义过滤器来复用这个功能:

1. 定义过滤器

angular.module('yourAppModule', [])
  .filter('capitalizeFirstWord', function() {
    return function(input) {
      if (!input) return input;
      // 可选基础字符串操作或正则方式,这里用基础方法
      return input.charAt(0).toUpperCase() + input.slice(1);
    };
  });

2. 在模板中使用

直接通过管道符调用过滤器:

<!-- 绑定变量或直接字符串 -->
<p>{{ userInput | capitalizeFirstWord }}</p>
<p>{{ 'angularjs filter demo' | capitalizeFirstWord }}</p>
<!-- 输出:Angularjs filter demo -->

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:25:27