是否有一个简单的方法来转换字符串标题大小写?例如,约翰·史密斯变成了约翰·史密斯。我不是在寻找像John Resig的解决方案那样复杂的东西,只是(希望)一些一两行代码。


当前回答

ES-6 way to get title case of a word or entire line.
ex. input = 'hEllo' --> result = 'Hello'
ex. input = 'heLLo woRLd' --> result = 'Hello World'

const getTitleCase = (str) => {
  if(str.toLowerCase().indexOf(' ') > 0) {
    return str.toLowerCase().split(' ').map((word) => {
      return word.replace(word[0], word[0].toUpperCase());
    }).join(' ');
  }
  else {
    return str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase();
  }
}

其他回答

这里有一个非常简单而简洁的ES6函数来做到这一点:

const titleCase = (str) => {
  return str.replace(/\w\S*/g, (t) => { return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase() });
}

export default titleCase;

工作良好,包括在一个实用程序文件夹,并使用如下:

import titleCase from './utilities/titleCase.js';

const string = 'my title & string';

console.log(titleCase(string)); //-> 'My Title & String'

这是个测试——>这是个测试

函数大写(str) { Const word = []; For (let char of str.split(' ')) { word.push(char[0].toUpperCase() + char.slice(1)) } 返回的词。加入(' '); } Console.log(大写("this is a test"));

以“lewax00”解决方案为例,我创建了这个简单的解决方案,强制以空格开头的“w”或初始化de word的“w”,但无法删除额外的中间空格。

"SOFÍA vergara".toLowerCase().replace(/\b(\s\w|^\w)/g, function (txt){返回txt. touppercase ();});

结果是“Sofía Vergara”。

与其他答案相比,我更喜欢下面的答案。它只匹配每个单词的第一个字母,并将其大写。更简单的代码,更容易阅读和更少的字节。它保留了现有的大写字母,以防止扭曲的首字母缩写。然而,你总是可以首先在你的字符串上调用toLowerCase()。

function title(str) {
  return str.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}

你可以把这个添加到你的字符串原型,这将允许你'my string'.toTitle()如下所示:

String.prototype.toTitle = function() {
  return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}

例子: String.prototype.toTitle = function() { return this.replace(/(^|\s)\ s /g, function(t) {return t. touppercase ()}); } console.log('全部小写->','全部小写'.toTitle()); console.log('所有大写字母->','所有大写字母'.toTitle()); console.log("I'm a little teapot ->","I'm a little teapot".toTitle());

Greg Dean的解决方案原型方案:

String.prototype.capitalize = function() {
  return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}