是否有一个简单的方法来转换字符串标题大小写?例如,约翰·史密斯变成了约翰·史密斯。我不是在寻找像John Resig的解决方案那样复杂的东西,只是(希望)一些一两行代码。
当前回答
首先,通过空格将字符串转换为数组:
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(“我是一个小/小茶壶。”));
其他回答
如果你需要一个语法正确的答案:
这个答案考虑了介词,如“of”,“from”,… 输出将生成您希望在论文中看到的编辑风格的标题。
toTitleCase函数
考虑此处列出的语法规则的函数。 该函数还合并空格和删除特殊字符(根据需要修改regex)
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');
});
});
请注意,我从提供的字符串中删除了相当多的特殊字符。您将需要调整正则表达式以满足项目的需求。
如果可以的话,我强烈建议使用开源的NPM包,这个包在typescript中工作得很好:
NPM: https://www.npmjs.com/package/title-case
Github: https://github.com/blakeembrey/change-case/tree/master/packages/title-case readme
运行npm install title-case将包添加到项目中。
使用标题大小写npm包的示例代码:
import { titleCase } from "title-case";
titleCase("string"); //=> "String"
titleCase("follow step-by-step instructions"); //=> "Follow Step-by-Step Instructions"
我已经为土耳其语测试了这个解决方案,它也适用于特殊字符。
function toTitleCase(str) 归来str replace (toLocaleLowerCase()。 - (^ | U | U |Ş|ş| |是C |İ|ı| |列传| w) \ S * / g, (txt) => txt.charAt(0)。 ) 的 控制台日志(toTitleCase(高中İİL HAKKI’) 控制台日志(toTitleCase(“ŞAHMARAN BİNBİR GECE MASALLARI”) 控制台日志(toTitleCase(“TEKNOLOJİURUNU”)
我在开头添加了“toLocaleLowerCase”,因为我所有的数据都是大写的。如果你不需要它,你可以丢弃它。
使用区域操作对于非英语语言很重要。
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");
var toMatch = "john w. smith";
var result = toMatch.replace(/(\w)(\w*)/g, function (_, i, r) {
return i.toUpperCase() + (r != null ? r : "");
}
)
似乎有用… 用上面的测试,“快棕色的狐狸?/跳过/越过了……“C:/程序文件/某些供应商/他们的第二个应用程序/a file1.txt”。
如果你想要2Nd而不是2Nd,你可以更改为/([a-z])(\w*)/g。
第一种形式可以简化为:
function toTitleCase(toTransform) {
return toTransform.replace(/\b([a-z])/g, function (_, initial) {
return initial.toUpperCase();
});
}
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔