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

时间:2008-10-13 08:05:03

标签: javascript title-case

有没有简单的方法将字符串转换为标题大小写?例如。 john smith变为John Smith。我不是在寻找像John Resig's solution那样复杂的东西,只是(希望)某种单行或双行。

63 个答案:

答案 0 :(得分:677)

试试这个:

    function toTitleCase(str) {
        return str.replace(
            /\w\S*/g,
            function(txt) {
                return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
            }
        );
    }
<form>
Input:
<br /><textarea name="input" onchange="form.output.value=toTitleCase(this.value)"  onkeyup="form.output.value=toTitleCase(this.value)"></textarea>
<br />Output:
<br /><textarea name="output" readonly onclick="select(this)"></textarea>
</form>

答案 1 :(得分:185)

一种稍微优雅的方式,适应Greg Dean的功能:

String.prototype.toProperCase = function () {
    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

称之为:

"pascal".toProperCase();

答案 2 :(得分:149)

尝试将text-transform CSS样式应用于您的控件。

例如:(text-transform: capitalize);

绝对必要时才使用JS方法。

答案 3 :(得分:92)

这是我的版本,IMO也很容易理解和优雅。

var str = "foo bar baz"

str.split(' ')
   .map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
   .join(' ')

// returns "Foo Bar Baz"

答案 4 :(得分:91)

这是我的函数,它转换为标题大小写,但也保留定义的首字母缩略词作为大写和小写单词作为小写:

String.prototype.toTitleCase = function() {
  var i, j, str, lowers, uppers;
  str = this.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });

  // Certain minor words should be left lowercase unless 
  // they are the first or last words in the string
  lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At', 
  'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
  for (i = 0, j = lowers.length; i < j; i++)
    str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), 
      function(txt) {
        return txt.toLowerCase();
      });

  // Certain words such as initialisms or acronyms should be left uppercase
  uppers = ['Id', 'Tv'];
  for (i = 0, j = uppers.length; i < j; i++)
    str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), 
      uppers[i].toUpperCase());

  return str;
}

例如:

"TO LOGIN TO THIS SITE and watch tv, please enter a valid id:".toTitleCase();
// Returns: "To Login to This Site and Watch TV, Please Enter a Valid ID:"

答案 5 :(得分:32)

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

答案 6 :(得分:17)

令人惊讶的是,没有人提到使用rest参数。这是一个使用ES6 Rest参数的简单衬垫。

let str="john smith"
str=str.split(" ").map(([firstChar,...rest])=>firstChar.toUpperCase()+rest.join("").toLowerCase()).join(" ")
console.log(str)

答案 7 :(得分:16)

不使用正则表达式仅供参考:

String.prototype.toProperCase = function() {
  var words = this.split(' ');
  var results = [];
  for (var i=0; i < words.length; i++) {
      var letter = words[i].charAt(0).toUpperCase();
      results.push(letter + words[i].slice(1));
  }
  return results.join(' ');
};

'john smith'.toProperCase();

答案 8 :(得分:15)

如果您担心这些填充词,您可以随时告诉该功能不要大写。

/**
 * @param String str The text to be converted to titleCase.
 * @param Array glue the words to leave in lowercase. 
 */
var titleCase = function(str, glue){
    glue = (glue) ? glue : ['of', 'for', 'and'];
    return str.replace(/(\w)(\w*)/g, function(_, i, r){
        var j = i.toUpperCase() + (r != null ? r : "");
        return (glue.indexOf(j.toLowerCase())<0)?j:j.toLowerCase();
    });
};

希望这可以帮助你。

修改

如果你想处理领先的胶水词,你可以跟踪这个w /还有一个变量:

var titleCase = function(str, glue){
    glue = !!glue ? glue : ['of', 'for', 'and', 'a'];
    var first = true;
    return str.replace(/(\w)(\w*)/g, function(_, i, r) {
        var j = i.toUpperCase() + (r != null ? r : '').toLowerCase();
        var result = ((glue.indexOf(j.toLowerCase()) < 0) || first) ? j : j.toLowerCase();
        first = false;
        return result;
    });
};

答案 9 :(得分:14)

如果上述解决方案中使用的正则表达式让您感到困惑,请尝试以下代码:

function titleCase(str) {
  return str.split(' ').map(function(val){ 
    return val.charAt(0).toUpperCase() + val.substr(1).toLowerCase();
  }).join(' ');
}

答案 10 :(得分:14)

这仅适用于一个单词字符串,但这就是我所需要的:

'string'.replace(/^[a-z]/, function (x) {return x.toUpperCase()}) // String

JSFiddle: https://jsfiddle.net/simo/gou2uhLm/

答案 11 :(得分:10)

您可以立即toLowerCase字符串,然后只需toUpperCase每个单词的第一个字母。成为一个非常简单的1班轮:

&#13;
&#13;
function titleCase(str) {
  return str.toLowerCase().replace(/\b(\w)/g, s => s.toUpperCase());
}

console.log(titleCase('iron man'));
console.log(titleCase('iNcrEdible hulK'));
&#13;
&#13;
&#13;

答案 12 :(得分:8)

我制作了这个可以处理姓氏的功能(所以它不是标题案例),例如“麦当劳”或“麦克唐纳”或“奥图尔”或“德奥拉齐奥”。然而,它并不处理带有“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(); });
}

答案 13 :(得分:7)

试试这个

String.prototype.toProperCase = function(){
    return this.toLowerCase().replace(/(^[a-z]| [a-z]|-[a-z])/g, 
        function($1){
            return $1.toUpperCase();
        }
    );
};

实施例

var str = 'john smith';
str.toProperCase();

答案 14 :(得分:7)

尝试这个,最短路:

str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase());

答案 15 :(得分:7)

var toMatch = "john w. smith";
var result = toMatch.replace(/(\w)(\w*)/g, function (_, i, r) {
      return i.toUpperCase() + (r != null ? r : "");
    }
)

似乎工作...... 经过上面的测试,“快速的棕色,狐狸?/跳跃/ ^超过'懒惰!狗......”和“C:/程序文件/某些供应商/他们的第二个应用程序/文件1.txt”。 / p>

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

第一种形式可以简化为:

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

答案 16 :(得分:7)

ES 6

str.split(' ')
   .map(s => s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase())
   .join(' ')

否则

str.split(' ').map(function (s) {
    return s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase();
}).join(' ')

答案 17 :(得分:6)

这些答案中的大多数似乎忽略了使用单词边界元字符(\ b)的可能性。 Greg Dean使用它的简短版本的答案:

function toTitleCase(str)
{
    return str.replace(/\b\w/g, function (txt) { return txt.toUpperCase(); });
}

适用于像Jim-Bob这样的带连字符的名字。

答案 18 :(得分:6)

我认为最简单的就是使用css。

function format_str(str) {
    str = str.toLowerCase();
    return '<span style="text-transform: capitalize">'+ str +'</span>';
}

答案 19 :(得分:5)

使用/\S+/g支持变音符号:

&#13;
&#13;
function toTitleCase(str) {
  return str.replace(/\S+/g, str => str.charAt(0).toUpperCase() + str.substr(1).toLowerCase());
}

console.log(toTitleCase("a city named örebro")); // A City Named Örebro
&#13;
&#13;
&#13;

然而:&#34; s unshine( y ellow)&#34; ⇒&#34; S unshine( y ellow)&#34;

答案 20 :(得分:5)

如果您可以在代码中使用第三方库,那么lodash为我们提供了帮助函数。

https://lodash.com/docs/4.17.3#startCase

_.startCase('foo bar');
// => 'Foo Bar'

_.startCase('--foo-bar--');
// => 'Foo Bar'
 
_.startCase('fooBar');
// => 'Foo Bar'
 
_.startCase('__FOO_BAR__');
// => 'FOO BAR'

答案 21 :(得分:4)

采用“lewax00”解决方案,我创建了这个简单的解决方案,迫使“w”以空格开头或“w”启动de word,但无法删除额外的中间空格。

"SOFÍA vergara".toLowerCase().replace(/\b(\s\w|^\w)/g, function (txt) { return txt.toUpperCase(); });

结果是“SofíaVergara”。

答案 22 :(得分:4)

将单个单词转换为首字母大写的简单方法

使用“切片”方法和字符串连接

str.slice(0, 1).toUpperCase() + str.slice(1, str.length)

*如果要小写其余单词,请在末尾添加.toLowerCase()

使用ES6 Spread运算符,映射和联接

[...str].map((w, i) => i === 0 ? w[0].toUpperCase() : w).join('')

答案 23 :(得分:3)

我想添加自己的答案,因为我需要一个强大的toTitleCase函数,该函数会考虑语法规则listed here(Google推荐文章)。有各种规则取决于输入字符串的长度。以下是功能+单元测试。

该函数还整合空格并删除特殊字符(根据需要修改正则表达式)

toTitleCase功能

const toTitleCase = (str) => {
  const articles = ['a', 'an', 'the'];
  const conjunctions = ['for', 'and', 'nor', 'but', 'or', 'yet', 'so'];
  const prepositions = [
    'with', 'at', 'from', 'into','upon', 'of', 'to', 'in', 'for',
    'on', 'by', 'like', 'over', 'plus', 'but', 'up', 'down', 'off', 'near'
  ];

  // The list of spacial characters can be tweaked here
  const replaceCharsWithSpace = (str) => str.replace(/[^0-9a-z&/\\]/gi, ' ').replace(/(\s\s+)/gi, ' ');
  const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.substr(1);
  const normalizeStr = (str) => str.toLowerCase().trim();
  const shouldCapitalize = (word, fullWordList, posWithinStr) => {
    if ((posWithinStr == 0) || (posWithinStr == fullWordList.length - 1)) {
      return true;
    }

    return !(articles.includes(word) || conjunctions.includes(word) || prepositions.includes(word));
  }

  str = replaceCharsWithSpace(str);
  str = normalizeStr(str);

  let words = str.split(' ');
  if (words.length <= 2) { // Strings less than 3 words long should always have first words capitalized
    words = words.map(w => capitalizeFirstLetter(w));
  }
  else {
    for (let i = 0; i < words.length; i++) {
      words[i] = (shouldCapitalize(words[i], words, i) ? capitalizeFirstLetter(words[i], words, i) : words[i]);
    }
  }

  return words.join(' ');
}

确保正确的单元测试

import { expect } from 'chai';
import { toTitleCase } from '../../src/lib/stringHelper';

describe('toTitleCase', () => {
  it('Capitalizes first letter of each word irrespective of articles, conjunctions or prepositions if string is no greater than two words long', function(){
    expect(toTitleCase('the dog')).to.equal('The Dog'); // Capitalize articles when only two words long
    expect(toTitleCase('for all')).to.equal('For All'); // Capitalize conjunctions when only two words long
    expect(toTitleCase('with cats')).to.equal('With Cats'); // Capitalize prepositions when only two words long
  });

  it('Always capitalize first and last words in a string irrespective of articles, conjunctions or prepositions', function(){
    expect(toTitleCase('the beautiful dog')).to.equal('The Beautiful Dog');
    expect(toTitleCase('for all the deadly ninjas, be it so')).to.equal('For All the Deadly Ninjas Be It So');
    expect(toTitleCase('with cats and dogs we are near')).to.equal('With Cats and Dogs We Are Near');
  });

  it('Replace special characters with space', function(){
    expect(toTitleCase('[wolves & lions]: be careful')).to.equal('Wolves & Lions Be Careful');
    expect(toTitleCase('wolves & lions, be careful')).to.equal('Wolves & Lions Be Careful');
  });

  it('Trim whitespace at beginning and end', function(){
    expect(toTitleCase(' mario & Luigi superstar saga ')).to.equal('Mario & Luigi Superstar Saga');
  });

  it('articles, conjunctions and prepositions should not be capitalized in strings of 3+ words', function(){
    expect(toTitleCase('The wolf and the lion: a tale of two like animals')).to.equal('The Wolf and the Lion a Tale of Two like Animals');
    expect(toTitleCase('the  three Musketeers  And plus ')).to.equal('The Three Musketeers and Plus');
  });
});

请注意我从提供的字符串中删除了相当多的特殊字符。您需要调整正则表达式以满足项目的要求。

答案 24 :(得分:3)

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

我们已经提出了几种不同类型的汽车资本化分散的案例,这些仅仅是英文名称,每种语言都有其复杂性。

将每个名字的第一个字母大写的问题:

•不允许输入IBM等缩略语,转为Ibm。

•麦当劳的名字会变成麦当劳,这是不正确的,麦克唐纳也是如此。

•像Marie-Tonks这样的双管名称会变成玛丽 - 唐克斯。

•像奥康纳这样的名字会变成奥康纳。

对于大多数这些,您可以编写自定义规则来处理它,但是,这仍然与以前一样存在缩略语问题,并且您遇到了一个新问题:

•添加规则来修复Mac的名称,例如麦克唐纳,像Macy这样的中断名称会将其变成MacY。

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

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

答案 25 :(得分:3)

对于我们这些害怕正则表达式的人(笑):

&#13;
&#13;
function titleCase(str)
{
    var words = str.split(" ");
    for ( var i = 0; i < words.length; i++ )
    {
        var j = words[i].charAt(0).toUpperCase();
        words[i] = j + words[i].substr(1);
    }
    return words.join(" ");
}
&#13;
&#13;
&#13;

答案 26 :(得分:3)

这是我的功能,它处理重音字符(对于法语很重要!),并且可以打开/关闭降低异常的处理。希望有所帮助。

String.prototype.titlecase = function(lang, withLowers = false) {
    var i, string, lowers, uppers;

    string = this.replace(/([^\s:\-'])([^\s:\-']*)/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    }).replace(/Mc(.)/g, function(match, next) {
        return 'Mc' + next.toUpperCase();
    });

    if (withLowers) {
        if (lang == 'EN') {
            lowers = ['A', 'An', 'The', 'At', 'By', 'For', 'In', 'Of', 'On', 'To', 'Up', 'And', 'As', 'But', 'Or', 'Nor', 'Not'];
        }
        else {
            lowers = ['Un', 'Une', 'Le', 'La', 'Les', 'Du', 'De', 'Des', 'À', 'Au', 'Aux', 'Par', 'Pour', 'Dans', 'Sur', 'Et', 'Comme', 'Mais', 'Ou', 'Où', 'Ne', 'Ni', 'Pas'];
        }
        for (i = 0; i < lowers.length; i++) {
            string = string.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), function(txt) {
                return txt.toLowerCase();
            });
        }
    }

    uppers = ['Id', 'R&d'];
    for (i = 0; i < uppers.length; i++) {
        string = string.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), uppers[i].toUpperCase());
    }

    return string;
}

答案 27 :(得分:2)

我的一线解决方案:

String.prototype.capitalizeWords = function() {
    return this.split(" ").map(function(ele){ return ele[0].toUpperCase() + ele.slice(1).toLowerCase();}).join(" ");
};

然后,您可以在任何字符串上调用方法capitalizeWords()。例如:

var myS = "this actually works!";
myS.capitalizeWords();

>>> This Actually Works

我的其他解决方案:

function capitalizeFirstLetter(word) {
    return word[0].toUpperCase() + word.slice(1).toLowerCase();
}
String.prototype.capitalizeAllWords = function() {
    var arr = this.split(" ");
    for(var i = 0; i < arr.length; i++) {
        arr[i] = capitalizeFirstLetter(arr[i]);
    }
    return arr.join(" ");
};

然后,您可以在任何字符串上调用方法capitalizeWords()。例如:

var myStr = "this one works too!";
myStr.capitalizeWords();

>>> This One Works Too

基于Greg Dean答案的替代解决方案:

function capitalizeFirstLetter(word) {
    return word[0].toUpperCase() + word.slice(1).toLowerCase();
}
String.prototype.capitalizeWords = function() {
    return this.replace(/\w\S*/g, capitalizeFirstLetter);
};

然后,您可以在任何字符串上调用方法capitalizeWords()。例如:

var myString = "yes and no";
myString.capitalizeWords()

>>> Yes And No

答案 28 :(得分:2)

首先,将string转换为数组splitting,然后按空格:

var words = str.split(' ');

然后使用array.map创建一个包含大写单词的新数组。

var capitalized = words.map(function(word) {
    return word.charAt(0).toUpperCase() + word.substring(1, word.length);
});

然后join新数组包含空格:

capitalized.join(" ");

function titleCase(str) {
  str = str.toLowerCase(); //ensure the HeLlo will become Hello at the end
  var words = str.split(" ");

  var capitalized = words.map(function(word) {
    return word.charAt(0).toUpperCase() + word.substring(1, word.length);
  });
  return capitalized.join(" ");
}

console.log(titleCase("I'm a little tea pot"));

注意:

这当然有一个缺点。这只会将每个单词的第一个字母大写。通过语言,这意味着它将我的空格分隔的每个字符串视为1个单词。

据说你有:

str = "I'm a little/small tea pot";

这将产生

  

我是一个小/ 茶壶

与预期相比

  

我是一个小/小茶壶

在这种情况下,使用Regex和.replace可以解决问题:

ES6:

const capitalize = str => str.length
  ? str[0].toUpperCase() +
    str.slice(1).toLowerCase()
  : '';

const escape = str => str.replace(/./g, c => `\\${c}`);
const titleCase = (sentence, seps = ' _-/') => {
  let wordPattern = new RegExp(`[^${escape(seps)}]+`, 'g');
  
  return sentence.replace(wordPattern, capitalize);
};
console.log( titleCase("I'm a little/small tea pot.") );

或没有 ES6

function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.substring(1, str.length).toLowerCase();
}

function titleCase(str) {
  return str.replace(/[^\ \/\-\_]+/g, capitalize);
}

console.log(titleCase("hello/hi world"));

答案 29 :(得分:2)

基准

TL; DR

该基准测试的获胜者是普通的for循环:

group = Group.objects.get(name="Student")
request.user.groups.add(group)

实际基准

我接受了最流行,最独特的答案,并用它们做出了a benchmark

这是我的MacBook Pro上的结果:

enter image description here

为完整起见,以下是使用的功能:

function titleize(str) {
    let upper = true
    let newStr = ""
    for (let i = 0, l = str.length; i < l; i++) {
        // Note that you can also check for all kinds of spaces  with
        // str[i].match(/\s/)
        if (str[i] == " ") {
            upper = true
            newStr += str[i]
            continue
        }
        newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase()
        upper = false
    }
    return newStr
}
// NOTE: you could beat that using charcode and string builder I guess.

请注意,我故意不更改原型,因为我认为这是非常糟糕的做法,并且我认为我们不应该在答案中推广这种做法。当您是唯一的小型代码库时,这是可以的。

如果您想在此基准测试中添加其他方法,请评论答案的链接!

答案 30 :(得分:2)

您可以将第一个字符大写并连接剩余的字符串。

let str = 'john smith';
let res = str.split(" ");
res.forEach((w, index) => {
    res[index] =  w.charAt(0).toUpperCase().concat(w.slice(1, w.length))
});
res = res.join(" ");
console.log(res);

答案 31 :(得分:2)

这是使用css(和javascript,如果要转换的文本为大写)的另一种解决方案:

html

<span id='text'>JOHN SMITH</span>

js

var str = document.getElementById('text').innerHtml;
var return_text = str.toLowerCase();

css

#text{text-transform:capitalize;}

答案 32 :(得分:2)

这是基于我对FreeCodeCamp's Bonfire "Title Case"的解决方案,它要求您首先将给定字符串转换为全部小写,然后将每个进行空格的字符转换为大写。

不使用正则表达式:

function titleCase(str) {
 return str.toLowerCase().split(' ').map(function(val) { return val.replace(val[0], val[0].toUpperCase()); }).join(' ');
}

答案 33 :(得分:2)

我对问题的简单易用版本:

    function titlecase(str){
    var arr=[];  
    var str1=str.split(' ');
    for (var i = 0; i < str1.length; i++) {
    var upper= str1[i].charAt(0).toUpperCase()+ str1[i].substr(1);
    arr.push(upper);
     };
      return arr.join(' ');
    }
    titlecase('my name is suryatapa roy');

答案 34 :(得分:1)

作为John Resig的解决方案的全功能,但作为一个单行:(基于this github project

function toTitleCase(e){var t=/^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i;return e.replace(/([^\W_]+[^\s-]*) */g,function(e,n,r,i){return r>0&&r+n.length!==i.length&&n.search(t)>-1&&i.charAt(r-2)!==":"&&i.charAt(r-1).search(/[^\s-]/)<0?e.toLowerCase():n.substr(1).search(/[A-Z]|\../)>-1?e:e.charAt(0).toUpperCase()+e.substr(1)})};

console.log( toTitleCase( "ignores mixed case words like iTunes, and allows AT&A and website.com/address etc..." ) );

答案 35 :(得分:1)

我的列表基于三个快速搜索。一个用于不被大写的单词列表,另一个用于一个完整的介词列表。

一个最终的搜索结果是建议,介词应该大写5个字母或更长,这是我喜欢的东西。我的目的是供非正式使用。我在他们中保留了“无”,因为这显然是与之对应的。

因此它使用首字母缩写词,标题的首字母和大多数单词的首字母。

它不用于处理大写锁定中的单词。我想让那些人呆着。

function camelCase(str) {
  return str.replace(/((?:^|\.)\w|\b(?!(?:a|amid|an|and|anti|as|at|but|but|by|by|down|for|for|for|from|from|in|into|like|near|nor|of|of|off|on|on|onto|or|over|past|per|plus|save|so|than|the|to|to|up|upon|via|with|without|yet)\b)\w)/g, function(character) {
  return character.toUpperCase();
})}
    
console.log(camelCase('The quick brown fox jumped over the lazy dog, named butter, who was taking a nap outside the u.s. Post Office. The fox jumped so high that NASA saw him on their radar.'));

答案 36 :(得分:1)

使用正则表达式的单一代码,获取单词\g的所有\b[a-zA-Z]起始字符,然后应用.toUpperCase()

const textString = "Convert string to title case with Javascript.";
const converted = textString.replace(/\b[a-zA-Z]/g, (match) => match.toUpperCase());
console.log(converted)

答案 37 :(得分:1)

this is a test ---> This Is A Test

function capitalize(str) {

  const word = [];

  for (let char of str.split(' ')) {
    word.push(char[0].toUpperCase() + char.slice(1))
  }

  return word.join(' ');

}

console.log(capitalize("this is a test"));

答案 38 :(得分:1)

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

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

function toUpperCase(str) { return str.toUpperCase(); }
function capitalizeWord(word) { return word.replace(/./, toUpperCase); }
function capitalize(sentence) { return sentence.toLowerCase().replace(/[^\s_\-/]*/g, capitalizeWord); }

console.log(capitalize("hello world")); // Outputs: Hello World

对于执行相同操作的单个函数,我们将replace调用嵌套如下:

function capitalize(sentence) {
  return sentence.toLowerCase().replace(/[^\s_\-/]*/g, function (word) {
    return word.replace(/./, function (ch) { return ch.toUpperCase(); } );
  } );
}

console.log(capitalize("hello world")); // Outputs: Hello World

答案 39 :(得分:1)

"john f. kennedy".replace(/\b\S/g, t => t.toUpperCase())

答案 40 :(得分:1)

这不短,但这是我最近在学校的任务中提出的:

var myPoem = 'What is a jQuery but a misunderstood object?'
//What is a jQuery but a misunderstood object? --> What Is A JQuery But A Misunderstood Object?

  //code here
var capitalize = function(str) {
  var strArr = str.split(' ');
  var newArr = [];
  for (var i = 0; i < strArr.length; i++) {
    newArr.push(strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1))
  };
  return newArr.join(' ')  
}

var fixedPoem = capitalize(myPoem);
alert(fixedPoem);

答案 41 :(得分:1)

以下是该问题的紧凑解决方案:

function Title_Case(phrase) 
{
  var revised = phrase.charAt(0).toUpperCase();

  for ( var i = 1; i < phrase.length; i++ ) {

    if (phrase.charAt(i - 1) == " ") {
     revised += phrase.charAt(i).toUpperCase(); }
    else {
     revised += phrase.charAt(i).toLowerCase(); }

   }

return revised;
}

答案 42 :(得分:1)

这是一个非常简单而简洁的ES6函数:

const titleCase = (str) => {
  return str.replace(/\w\S*/g, (t) => { return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase() });
}

export default titleCase;

很好地包含在utilities文件夹中,并按如下方式使用:

import titleCase from './utilities/titleCase.js';

const string = 'my title & string';

console.log(titleCase(string)); //-> 'My Title & String'

答案 43 :(得分:1)

这是我的回答。伙计们,请发表评论并喜欢,如果您的问题得到解决。

function toTitleCase(str) {
  return str.replace(
    /(\w*\W*|\w*)\s*/g,
    function(txt) {
    return(txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase())
    }
  ); 
}
<form>
  Input:
  <br /><textarea name="input" onchange="form.output.value=toTitleCase(this.value)" onkeyup="form.output.value=toTitleCase(this.value)"></textarea>
  <br />Output:
  <br /><textarea name="output" readonly onclick="select(this)"></textarea>
</form>

答案 44 :(得分:1)

Greg Dean解决方案的原型解决方案:

String.prototype.capitalize = function() {
  return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

答案 45 :(得分:1)

更简单,性能更高的版本,具有简单的缓存。

  var TITLE_CASE_LOWER_MAP = {
    'a': 1, 'an': 1, 'and': 1, 'as': 1, 'at': 1, 'but': 1, 'by': 1, 'en':1, 'with': 1,
    'for': 1, 'if': 1, 'in': 1, 'of': 1, 'on': 1, 'the': 1, 'to': 1, 'via': 1
  };

  // LEAK/CACHE TODO: evaluate using LRU.
  var TITLE_CASE_CACHE = new Object();

  toTitleCase: function (title) {
    if (!title) return null;

    var result = TITLE_CASE_CACHE[title];
    if (result) {
      return result;
    }

    result = "";
    var split = title.toLowerCase().split(" ");
    for (var i=0; i < split.length; i++) {

      if (i > 0) {
        result += " ";
      }

      var word = split[i];
      if (i == 0 || TITLE_CASE_LOWER_MAP[word] != 1) {
        word = word.substr(0,1).toUpperCase() + word.substr(1);
      }

      result += word;
    }

    TITLE_CASE_CACHE[title] = result;

    return result;
  },

答案 46 :(得分:1)

强大的功能编程方式Title Case Function

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'

答案 47 :(得分:0)

没有正则表达式,没有循环,没有拆分,没有子字符串:

{
    "lots": [
        {
            "lot": 0,
            "objects": [
                {
                    "price": 25.5,
                    "OKPD_code": "22.19.60.119-00000004",
                    "OKPD_name": "aaaaaaaaaa"
                },
                {
                    "price": 28.5,
                    "OKPD_code": "22.19.60.113-00000002",
                    "OKPD_name": "bbbbbbbbbb"
                },
                {
                    "price": 28.5,
                    "OKPD_code": "22.19.60.113-00000002",
                    "OKPD_name": "cccccccccc"
                },
                {
                    "price": 19,
                    "OKPD_code": "22.19.60.119-00000003",
                    "OKPD_name": "dddddddddd"
                },
                {
                    "price": 25.5,
                    "OKPD_code": "22.19.60.119-00000004",
                    "OKPD_name": "eeeeeeeeee"
                },
                {
                    "price": 15,
                    "OKPD_code": "22.19.60.119-00000010",
                    "OKPD_name": "ffffffffff"
                },
                {
                    "price": 15,
                    "OKPD_code": "22.19.60.119-00000010",
                    "OKPD_name": "gggggggggg"
                },
                {
                    "price": 24.5,
                    "OKPD_code": "22.19.60.119-00000008",
                    "OKPD_name": "hhhhhhhhhh"
                },
                {
                    "price": 24.5,
                    "OKPD_code": "22.19.60.119-00000008",
                    "OKPD_name": "jjjjjjjjjj"
                }
            ]
        }
    ],
    "customers": [
        {
            "customer_regNum": "03762000150",
            "customer_fullName": "ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ УЧРЕЖДЕНИЕ ЗДРАВООХРАНЕНИЯ РЕСПУБЛИКИ АДЫГЕЯ \"МАЙКОПСКАЯ ГОРОДСКАЯ КЛИНИЧЕСКАЯ БОЛЬНИЦА\""
        }
    ],
    "purchaseNumber": "0376200015021000029"
}

答案 48 :(得分:0)

我认为您应该尝试使用此功能。

var toTitleCase = function (str) {
    str = str.toLowerCase().split(' ');
    for (var i = 0; i < str.length; i++) {
        str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
    }
    return str.join(' ');
};

答案 49 :(得分:0)

我的回答使用正则表达式。

有关正则表达式的更多详细信息:https://regex101.com/r/AgRM3p/1

function toTitleCase(string = '') {
  const regex = /^[a-z]{0,1}|\s\w/gi;

  string = string.toLowerCase();

  string.match(regex).forEach((char) => {
    string = string.replace(char, char.toUpperCase());
  });

  return string;
}

const input = document.getElementById('fullname');
const button = document.getElementById('button');
const result = document.getElementById('result');

button.addEventListener('click', () => {
  result.innerText = toTitleCase(input.value);
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
</head>
<body>
    <input type="text" id="fullname">
    <button id="button">click me</button>
    <p id="result">Result here</p>
    <script src="./index.js"></script>
</body>
</html>

答案 50 :(得分:0)

boost::variant

用法:

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

答案 51 :(得分:0)

使用lodash的解决方案-

import { words, lowerCase, capitalize, endsWith, padEnd } from 'lodash';
const titleCase = string =>
  padEnd(
    words(string, /[^ ]+/g)
      .map(lowerCase)
      .map(capitalize)
      .join(' '),
    string.length,
  );

答案 52 :(得分:0)

约翰·史密斯->约翰·史密斯

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

答案 53 :(得分:0)

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

答案 54 :(得分:0)

另一种实现类似目的的方法如下。

formatName(name) {
    let nam = '';
    name.split(' ').map((word, index) => {
        if (index === 0) {
            nam += word.split('').map((l, i) => i === 0 ? l.toUpperCase() : l.toLowerCase()).join('');
        } else {
            nam += ' ' + word.split('').map(l => l.toLowerCase()).join('');
        }
    });
    return nam;
}

答案 55 :(得分:0)

一种方法使用reduce

function titleCase(str) {
  const arr = str.split(" ");
  const result = arr.reduce((acc, cur) => {
    const newStr = cur[0].toUpperCase() + cur.slice(1).toLowerCase();
    return acc += `${newStr} `
  },"")
  return result.slice(0, result.length-1);
}

答案 56 :(得分: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. */

答案 57 :(得分: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");

答案 58 :(得分:0)

这是一个行解决方案,如果你想转换字符串中的每个工作,用“”拆分字符串,迭代部分并将此解决方案应用于每个部分,将每个转换的部分添加到数组并将其与“ ”

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

答案 59 :(得分: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;
}

答案 60 :(得分:-1)

https://lodash.com/docs/4.17.11#capitalize

使用Lodash库.. !!更可靠

_.capitalize('FRED'); => 'Fred'

答案 61 :(得分:-1)

ES6 one liner

const toTitleCase = string => string.split(' ').map((word) => [word[0].toUpperCase(), ...word.substr(1)].join('')).join(' ');

答案 62 :(得分:-1)

添加到混音中的另一个版本。这也将检查string.length是否为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);
};