仅当 lengh > 2 时,Javascript 才将字符串中每个单词的第一个字母大写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17200640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:27:48  来源:igfitidea点击:

Javascript capitalize first letter of each word in a string only if lengh > 2

javascriptregex

提问by Conrado Fonseca

I looked at some questions and answers about capitalize in StackOverflow but could not find answer about my problem.

我在 StackOverflow 中查看了一些有关大写的问题和答案,但找不到有关我的问题的答案。

I would like to capitalize first letter of each word in a string only if word lengh > 2.

仅当单词 lengh > 2 时,我才想将字符串中每个单词的第一个字母大写。

My temporary solution was:

我的临时解决方案是:

var str =  str.toLowerCase().replace(/\b[a-z]/g, function (letter) {
                return letter.toUpperCase();
            }).replace(/\b\w{1,2}\b/g, function (letter) {
                return letter.toLowerCase();
            });

There is a solution that can unite the two regex in one?

有没有可以将两个正则表达式合二为一的解决方案?

回答by Casimir et Hippolyte

This must do the job:

这必须完成这项工作:

str = str.toLowerCase().replace(/\b[a-z](?=[a-z]{2})/g, function(letter) {
    return letter.toUpperCase(); } );

[EDIT]

[编辑]

The above example is a little naive since it assumes that there is only letters in the string, and doesn't take account that a word boundary \bcan match the limit between a word character [a-zA-Z0-9_]and a non word character or an anchor. Thus, to be more rigorous, it's better to write:

上面的例子有点幼稚,因为它假设字符串中只有字母,并且没有考虑单词边界\b可以匹配单词字符[a-zA-Z0-9_]和非单词字符或锚点之间的限制。因此,为了更严谨,最好这样写:

str = str.toLowerCase().replace(/([^a-z]|^)([a-z])(?=[a-z]{2})/g, function(_, g1, g2) {
    return g1 + g2.toUpperCase(); } );

If you want to do the same but this time, including the first letter of the string (whatever the number of letters after) you can use this:

如果你想这样做,但这次,包括字符串的第一个字母(无论后面的字母数量如何),你可以使用:

str = str.toLowerCase().replace(/([^a-z])([a-z])(?=[a-z]{2})|^([a-z])/g, function(_, g1, g2, g3) {
    return (typeof g1 === 'undefined') ? g3.toUpperCase() : g1 + g2.toUpperCase(); } );

回答by Matteo Tassinari

Try this:

试试这个:

var str = str.toLowerCase().replace(/\b\w{3,}/g, function (l) {
    return l.charAt(0).toUpperCase() + l.slice(1);
});

回答by AntouanK

Maybe use a function to make it more clean

也许使用一个函数让它更干净

var capitalize1st = function(str){
    str = str || '';

    // string length must be more than 2
    if(str.length<3){
        return str;
    }

    return str[0].toUpperCase()+str.slice(1);
}

var splitWordsAndCap1st = function(str){
    str = str || '';

    var words = str.match(/\S+/g);

    for(var i=0;i<words.length;i++){
        words[i] = capitalize1st(words[i]);
    }

    return words.join(' ');
}

splitWordsAndCap1st("I would like to capitalize first letter of each word in a string");

回答by Hitesh Kumar

Here's a simpler solution which does the job.

这是一个更简单的解决方案,可以完成这项工作。

const capitalize = (str) =>
  str.toLowerCase().replace(/\w{3,}/g, (match) =>
    match.replace(/\w/, (m) => m.toUpperCase()));

回答by Xotic750

No need for regex (just one small one to capture whitespace), you could do this

不需要正则表达式(只需要一小部分来捕获空格),你可以这样做

Javascript

Javascript

function titleCaseLengthGt2(string) {
    var array = string.split(/(\s+)/),
        length = array.length,
        i = 0,
        word;

    while (i < length) {
        //array[i] = array[i].toLowerCase(); // make words lowercased first if you want
        word = array[i];
        if (word.length > 2) {
            array[i] = word.charAt(0).toUpperCase() + word.slice(1);
        }

        i += 1;
    }

    return array.join("");
}

console.log(titleCaseLengthGt2("i  want  to  be  titelised"));

Output

输出

i  Want  to  be  Titelised 

on jsfiddle

jsfiddle 上

回答by Pierre Forestier

To capitalize first letter of each word in a string if word length > 2, I use for english text:

如果单词长度 > 2,要大写字符串中每个单词的第一个字母,我使用英文文本:

l_text = l_text.toLowerCase().replace(/(?=\b)([a-z])(?=[a-z]{2})/g, 
     function(g0) {return (g0.toUpperCase());});

Often in real life the rule "word length > 2" is not enough.

在现实生活中,规则“字长> 2”通常是不够的。

To capitalize town names in french I have to exclude some words like in this sample:

为了在法语中大写城镇名称,我必须排除一些像在这个示例中的单词:

l_text = "Bourg-en-Bresse, NEUILLY SUR SEINE, enghien-les-bains";
l_text = l_text.toLowerCase().replace(/(?=\b)(?!(?:d|en|les|sous|sur)\b)([a-z])/g,
     function(g0) {return (g0.toUpperCase());});

For a more sophisticated situation, you may combine the negative lookahead assertion (?!(:|en|les|sous|sur)\b) and the positive lookahead assertion (?=[a-z]{2}).

对于更复杂的情况,您可以组合否定先行断言 (?!(:|en|les|sous|sur)\b) 和肯定先行断言 (?=[az]{2})。

To deal with non standard word boundary and characters out of a-z range, you may use a word boundary and characters set specific to the context:

要处理非标准词边界和 az 范围外的字符,您可以使用特定于上下文的词边界和字符集:

/(?:^|[\s'\-])(?!(?:d|en|les|sous|sur)[\s'\-])([a-zàaéèê??ù??])/g