使用JavaScript将字符串转换为标题大小写

779

有没有一种简单的方法将字符串转换为标题格式?例如,john smith 变成 John Smith。我不想要像John Resig的解决方案那样复杂的东西,只是(希望)一种一两行代码就能实现的方法。


1
有许多方法,我们有一些性能统计数据吗? - theAnubhav
1
@theAnubhav 是的,我们现在有一个基准 - Ulysse BN
2
到了2022年,浏览器仍然没有本地功能来执行此操作。 - Sơn Trần-Nguyễn
1
这种大小写格式完全取决于语言/地点/文化。 - James Moore
我希望解决方案的一个测试用例是“Comhrá i mBÁC le Seán Nguyen” - 祝你好运!基本上,计算机可以执行称为“标题大小写”的操作的想法可能是没有希望的,即使给定了大量的机器学习资源。 - James Moore
69个回答

1

John Smith -> 约翰·史密斯

'john smith'.replace(/(^\w|\s+\w){1}/g, function(str){ return str.toUpperCase() } );

1
一种使用lodash的解决方案 -
import { words, lowerCase, capitalize, endsWith, padEnd } from 'lodash';
const titleCase = string =>
  padEnd(
    words(string, /[^ ]+/g)
      .map(lowerCase)
      .map(capitalize)
      .join(' '),
    string.length,
  );

为什么不使用_.startCase('john smith');呢?https://lodash.com/docs/4.17.15#startCase - w3debugger
_.startCase会删除字符串中的任何特殊字符。例如:_.startCase('john-smith') => John Smith。但是,如果整个字符串都是大写的,并且您只想将第一个字符大写,那么startCase就无法帮助您了。例如:_.startCase('JOHN SMITH') => JOHN SMITH - Avinash
啊,我不知道大写字母的问题。但是在这种情况下,我们可以使用 _.startCase('HELLO'.toLowerCase()) 吗? - w3debugger

0
String.prototype.capitalize = function() {
    return this.toLowerCase().split(' ').map(capFirst).join(' ');
    function capFirst(str) {
        return str.length === 0 ? str : str[0].toUpperCase() + str.substr(1);
    }
}

使用方法:

"hello world".capitalize()

除了 String.prototype 部分以外都很好。不要搞乱内置对象! - Travis Webb

0
function titleCase(str) {
    str = str.toLowerCase();

    var strArray = str.split(" ");


    for(var i = 0; i < strArray.length; i++){
        strArray[i] = strArray[i].charAt(0).toUpperCase() + strArray[i].substr(1);

    }

    var result = strArray.join(" ");

    //Return the string
    return result;
}

0

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

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

0

一种强大的函数式编程方法来实现标题大小写函数

说明版本

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
}

Implementation version

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

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

为什么不直接使用 function toTitleCase(input){ return input.....join(' ') } 呢? - mplungjan

0

又是另一个版本加入到混合中。这也会检查字符串长度是否为0:

String.prototype.toTitleCase = function() {
    var str = this;
    if(!str.length) {
        return "";
    }
    str = str.split(" ");
    for(var i = 0; i < str.length; i++) {
        str[i] = str[i].charAt(0).toUpperCase() + (str[i].substr(1).length ? str[i].substr(1) : '');
    }
    return (str.length ? str.join(" ") : str);
};

0
function toTitleCase(str) {
  var strnew = "";
  var i = 0;

  for (i = 0; i < str.length; i++) {
    if (i == 0) {
      strnew = strnew + str[i].toUpperCase();
    } else if (i != 0 && str[i - 1] == " ") {
      strnew = strnew + str[i].toUpperCase();
    } else {
      strnew = strnew + str[i];
    }
  }

  alert(strnew);
}

toTitleCase("hello world how are u");

0
将文本转换为标题大小写,即将每个单词的首字母转换为大写,并将其余字符转换为小写。 "首字母" 定义为不以单词字符开头的字符;可以通过 "负向后行断言" 进行匹配。
实现方式如下:
- 将 "单词字符" 定义为非空白字符(即非 \s,即 \S)。
function toTitleCase(text) {
  return text.toLowerCase().replace(
    /(?<!\S)\S/ug, match => match.toUpperCase()
  );
}


toTitleCase('don’t perform input–output ’til out-of-memory');
// 'Don’t Perform Input–output ’til Out-of-memory'
  • 对于定义为非空格和非破折号标点符号(即不是\s和不是\p{Pd},即[^\s\p{Pd}])的单词字符的实现:
function toTitleCase(text) {
  return text.toLowerCase().replace(
    /(?<![^\s\p{Pd}])[^\s\p{Pd}]/ug, match => match.toUpperCase()
  );
}


toTitleCase('don’t perform input–output ’til out-of-memory');
// 'Don’t Perform Input–Output ’til Out-Of-Memory'

试试这个‘džungla’。 - user3840170
@user3840170 它返回了 'DŽungla'。你期望得到什么? - undefined

0
这是一行解决方案,如果您想将字符串中的每个单词转换,可以通过“ ”拆分字符串,迭代各部分并对每个部分应用此解决方案,将每个转换后的部分添加到数组中,并使用“ ”连接。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接