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


当前回答

这里有一个紧凑的解决方案:

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

其他回答

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

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

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

最后一个搜索建议,5个或5个字母以上的介词应该大写,这是我喜欢的。我的目的是非正式使用。我把“without”留在了他们的单词里,因为它是with的明显对应词。

所以它把首字母缩写,标题的第一个字母,以及大多数单词的第一个字母都大写。

它不打算处理带有大写锁的单词。我不想管这些。

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.'));

与John Resig的解决方案一样功能齐全,但作为一行程序:(基于此github项目)

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..." ) );

Var结果= “这很有趣”。/\b[a-z]/g, (x) => x. touppercase ()) console.log(result) // This Is Very Interesting

一种稍微优雅一点的方式,改编了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();