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


当前回答

如果你想使用NPM库,请查看title-case:

安装:

npm install title-case --save

用法:

import { titleCase } from "title-case";

titleCase("string"); //=> "String"
titleCase("follow step-by-step instructions"); //=> "Follow Step-by-Step Instructions"

其他回答

以“lewax00”解决方案为例,我创建了这个简单的解决方案,强制以空格开头的“w”或初始化de word的“w”,但无法删除额外的中间空格。

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

结果是“Sofía Vergara”。

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

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

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

一个使用lodash -的解决方案

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

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

最后一个搜索建议,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.'));