如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?

例如:

“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”


当前回答

一个简单的,紧凑的功能,将完成你的工作:

const capitalize = str => str.split(' ').map(sub => sub.charAt(0).toUpperCase() + sub.slice(1)).join(' ');

“Foo” > “Foo” “Foo Bar” > “Foo Bar”

其他回答

我們可以獲得第一個角色與我最喜歡的RegExp之一,看起來像一個可愛的微笑: /^./

String.prototype.capitalize = function () {
  return this.replace(/^./, function (match) {
    return match.toUpperCase();
  });
};

对于所有咖啡豆:

String::capitalize = ->
  @replace /^./, (match) ->
    match.toUpperCase()

...和所有认为有更好的方式做到这一点的男孩,没有扩展原生原型:

var capitalize = function (input) {
  return input.replace(/^./, function (match) {
    return match.toUpperCase();
  });
};

好吧,所有答案都会崩溃,如果方法通过一些意想不到的数据类型,如对象或功能。

因此,要确保它不会在任何情况下崩溃,我们将需要检查类型。

首頁 〉外文書 〉文學 〉文學 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉

你可以做 str.replace(str[0], str[0].toUpperCase())。

看看这个例子:

let str = “Hello, WORLD!” let newStr = str.replace(str[0], str[0].toUpperCase()) console.log(“str:”, str) console.log(“newStr:”, newStr)

function capitalize(s) {
    // returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
    return s[0].toUpperCase() + s.substr(1);
}


// examples
capitalize('this is a test');
=> 'This is a test'

capitalize('the Eiffel Tower');
=> 'The Eiffel Tower'

capitalize('/index.html');
=> '/index.html'

此代码还将在链条的开始和结束时处理额外的空间。

讓 val ='這是測試'; val = val.trim(); val = val.charAt(0).toUpperCase() + val.slice(1); console.log("Value => ", val);