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


当前回答

吉姆-鲍勃->吉姆-鲍勃

吉姆/鲍勃->吉姆/鲍勃

jim_bob -> jim_bob

不是->不是

学校->学校

麦当劳->麦当劳

function toTitleCase(str) {
  return str.replace(/\p{L}+('\p{L}+)?/gu, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.slice(1)
  })
}

其他回答

你可以立即toLowerCase字符串,然后只是toUpperCase每个单词的第一个字母。变成了非常简单的一行:

函数titleCase(str) { 返回str.toLowerCase()。/\b\w/g, s => s. touppercase ()); } console.log (titleCase(‘钢铁侠’); console.log (titleCase(“绿巨人”);

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

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

如果你想使用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"

首先,通过空格将字符串转换为数组:

var words = str.split(' ');

然后使用数组。映射以创建包含大写单词的新数组。

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

然后用空格连接新数组:

capitalized.join(" ");

函数titleCase(str) { str = str. tolowercase ();//确保HeLlo在结束时变成HeLlo Var words = str.split(" "); Var大写= words.map(函数(词){ 返回word. charat (0). touppercase () + word. charat。substring(1、word.length); }); 返回大写。加入(" "); } console.log(titleCase(“我是一个小茶壶”));

注意:

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

假设你有:

str = "我是一个小/小茶壶";

这将产生

我是一个小茶壶

与预期相比

我是一个小茶壶

在这种情况下,使用Regex和.replace就可以了:

ES6:

STR .length => ? str [0] .toUpperCase () + str.slice (1) .toLowerCase () :”; STR .replace(/。/g, c => ' \\${c} '); const titleCase =(句子,seps = ' _-/') => { 让wordPattern = new RegExp(“[^ ${逃脱(seps)}] + ', ' g '); 返回的句子。替换(wordPattern,大写); }; console.log(titleCase(“我是一个小/小茶壶。”));

或不含ES6:

函数大写(str) { 返回str.charAt(0).toUpperCase() + str.substring(1, str.length).toLowerCase(); } 函数titleCase(str) { 返回str.replace(/[^\ \/\-\_]+/g,大写); } console.log(titleCase(“我是一个小/小茶壶。”));

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

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