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


当前回答

试试这个:

function toTitleCase(str) str归来。replace ( - w \ S * / g, 功能(. txt) { 归来txt.charAt(0). toupfaith (+ txt.substr) 的 ); 的 < form > 输入: <br /><textarea" > < / textarea > < br / >输出: <br /><textarea" > < / textarea > < / form >

其他回答

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

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

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'

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

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. */

有一些很好的答案,但是,许多人使用正则表达式来查找单词,但是,由于某种原因,没有人使用正则表达式来替换第一个字符。为了解释,我将提供一个较长的解决方案和一个较短的解决方案。

长期解决方案(更具解释性)。通过使用正则表达式[^\s_\-/]*,我们可以找到句子中的每一个单词。随后,我们可以使用正则表达式。与单词中的第一个字符匹配。使用正则表达式版本的replace来替换这两个函数,我们可以像这样更改解决方案:

function toUpperCase(str){返回str.toUpperCase();} 函数capitalizeWord(word){返回word.replace(/。/,包含);} 函数大写(句子){返回句子。tolowercase()。替换(/ [/ ^ \ s_ \] * / g, capitalizeWord);} console.log(大写(“hello world”));//输出:Hello World

对于做同样事情的单个函数,我们将replace调用嵌套如下:

函数大写(句子){ 返回sentence.toLowerCase()。替换(/[^\s_\-/]*/g, function (word) { 返回word.replace(/。/,函数(ch){返回ch. touppercase ();}); }); } console.log(大写(“hello world”));//输出:Hello World

惊讶地看到没有人提到rest参数的使用。下面是一个简单的使用ES6 Rest参数的程序。

让我们看《约翰·史密斯》 str = str。劈(“”)。([firstChar文件夹,...休息)= > firstChar toUpperCase() +休息。加入toLowerCase()(“”)。加入(“”) 控制台日志(str)。