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


当前回答

这个解决方案将标点符号考虑到新句子中,处理引用,将小词转换为小写,忽略首字母缩写或全大写单词。

var stopWordsArray = new Array("a", "all", "am", "an", "and", "any", "are", "as", "at", "be", "but", "by", "can", "can't", "did", "didn't", "do", "does", "doesn't", "don't", "else", "for", "get", "gets", "go", "got", "had", "has", "he", "he's", "her", "here", "hers", "hi", "him", "his", "how", "i'd", "i'll", "i'm", "i've", "if", "in", "is", "isn't", "it", "it's", "its", "let", "let's", "may", "me", "my", "no", "of", "off", "on", "our", "ours", "she", "so", "than", "that", "that's", "thats", "the", "their", "theirs", "them", "then", "there", "there's", "these", "they", "they'd", "they'll", "they're", "they've", "this", "those", "to", "too", "try", "until", "us", "want", "wants", "was", "wasn't", "we", "we'd", "we'll", "we're", "we've", "well", "went", "were", "weren't", "what", "what's", "when", "where", "which", "who", "who's", "whose", "why", "will", "with", "won't", "would", "yes", "yet", "you", "you'd", "you'll", "you're", "you've", "your");

// Only significant words are transformed. Handles acronyms and punctuation
String.prototype.toTitleCase = function() {
    var newSentence = true;
    return this.split(/\s+/).map(function(word) {
        if (word == "") { return; }
        var canCapitalise = true;
        // Get the pos of the first alpha char (word might start with " or ')
        var firstAlphaCharPos = word.search(/\w/);
        // Check for uppercase char that is not the first char (might be acronym or all caps)
        if (word.search(/[A-Z]/) > 0) {
            canCapitalise = false;
        } else if (stopWordsArray.indexOf(word) != -1) {
            // Is a stop word and not a new sentence
            word.toLowerCase();
            if (!newSentence) {
                canCapitalise = false;
            }
        }
        // Is this the last word in a sentence?
        newSentence = (word.search(/[\.!\?:]['"]?$/) > 0)? true : false;
        return (canCapitalise)? word.replace(word[firstAlphaCharPos], word[firstAlphaCharPos].toUpperCase()) : word;
    }).join(' ');
}

// Pass a string using dot notation:
alert("A critical examination of Plato's view of the human nature".toTitleCase());
var str = "Ten years on: a study into the effectiveness of NCEA in New Zealand schools";
str.toTitleCase());
str = "\"Where to from here?\" the effectivness of eLearning in childhood education";
alert(str.toTitleCase());

/* Result:
A Critical Examination of Plato's View of the Human Nature.
Ten Years On: A Study Into the Effectiveness of NCEA in New Zealand Schools.
"Where to From Here?" The Effectivness of eLearning in Childhood Education. */

其他回答

健壮的函数式编程方式做标题大小写函数

Exaplin版本

function toTitleCase(input){
    let output = input
        .split(' ')  // 'HOw aRe YOU' => ['HOw' 'aRe' 'YOU']
        .map((letter) => {
            let firstLetter = letter[0].toUpperCase() // H , a , Y  => H , A , Y
            let restLetters = letter.substring(1).toLowerCase() // Ow, Re, OU => ow, re, ou
            return firstLetter + restLetters // conbine together
        })
        .join(' ') //['How' 'Are' 'You'] => 'How Are You'
    return output
}

实现版本

function toTitleCase(input){
    return input
            .split(' ')
            .map(i => i[0].toUpperCase() + i.substring(1).toLowerCase())
            .join(' ') 
}

toTitleCase('HoW ARe yoU') // reuturn 'How Are You'

我做了这个函数,它可以处理姓氏(所以它不是标题大小写),如“McDonald”或“MacDonald”或“O'Toole”或“D'Orazio”。然而,它不能处理带有“van”或“von”的德语或荷兰语名称,这些名称通常是小写的。我相信“de”也经常是小写的,比如“Robert de Niro”。这些问题仍需解决。

function toProperCase(s)
{
  return s.toLowerCase().replace( /\b((m)(a?c))?(\w)/g,
          function($1, $2, $3, $4, $5) { if($2){return $3.toUpperCase()+$4+$5.toUpperCase();} return $1.toUpperCase(); });
}
var toMatch = "john w. smith";
var result = toMatch.replace(/(\w)(\w*)/g, function (_, i, r) {
      return i.toUpperCase() + (r != null ? r : "");
    }
)

似乎有用… 用上面的测试,“快棕色的狐狸?/跳过/越过了……“C:/程序文件/某些供应商/他们的第二个应用程序/a file1.txt”。

如果你想要2Nd而不是2Nd,你可以更改为/([a-z])(\w*)/g。

第一种形式可以简化为:

function toTitleCase(toTransform) {
  return toTransform.replace(/\b([a-z])/g, function (_, initial) {
      return initial.toUpperCase();
  });
}

我们已经在办公室进行了讨论,我们认为试图自动纠正人们输入姓名的方式,以您希望的方式进行,这可能充满了问题。

我们已经提出了几种不同类型的自动大写不成立的情况,这些仅仅是英语名称,每种语言都有自己的复杂性。

每个名字首字母大写的问题:

•像IBM这样的首字母缩写不允许输入,会变成IBM。

•McDonald这个名字会变成McDonald,这是不正确的,同样的东西也是MacDonald。

•像Marie-Tonks这样的双筒名字会变成Marie-Tonks。

O 'Connor这样的名字会变成O 'Connor。

对于其中的大多数,你可以编写自定义规则来处理它,然而,这仍然与以前的缩略语有问题,你会得到一个新的问题:

•添加一个规则来修复Mac的名称,如MacDonald,将打破名称,如Macy,将其变成Macy。

我们提出的唯一解决方案是永远不会不正确的是大写每一个字母,这是一个蛮力的方法,DBS似乎也使用。

因此,如果你想自动化这个过程,没有一个字典,每个名字和单词,以及它应该如何大写,这是不可能的。如果你没有一个规则,涵盖一切,不要使用它,因为它只会惹恼你的用户,并提示那些想要正确输入他们的名字的人去其他地方。

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();
  }
}