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


当前回答

这是一行解决方案,如果你想转换字符串中的每个工作,用“”分割字符串,遍历部分并将此解决方案应用到每个部分,将每个转换的部分添加到一个数组中,并与“”连接。

var stringToConvert='john'; stringToConvert = stringToConvert.charAt(0).toUpperCase() + Array.prototype.slice.call(stringToConvert, 1).join(''); console.log(stringToConvert);

其他回答

如果一个CSS解决方案满足你的需求,你可以应用文本转换CSS样式到你的控件:

text-transform: capitalize;

请注意,这将会改变: hello world到hello world HELLO WORLD到HELLO WORLD(不变) emily-jane o'brien致emily-jane o'brien(不正确) 玛丽亚·冯·特拉普写给玛丽亚·冯·特拉普(不正确)

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

我已经为土耳其语测试了这个解决方案,它也适用于特殊字符。

function toTitleCase(str) 归来str replace (toLocaleLowerCase()。 - (^ | U | U |Ş|ş| |是C |İ|ı| |列传| w) \ S * / g, (txt) => txt.charAt(0)。 ) 的 控制台日志(toTitleCase(高中İİL HAKKI’) 控制台日志(toTitleCase(“ŞAHMARAN BİNBİR GECE MASALLARI”) 控制台日志(toTitleCase(“TEKNOLOJİURUNU”)

我在开头添加了“toLocaleLowerCase”,因为我所有的数据都是大写的。如果你不需要它,你可以丢弃它。

使用区域操作对于非英语语言很重要。

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'