是否有一个简单的方法来转换字符串标题大小写?例如,约翰·史密斯变成了约翰·史密斯。我不是在寻找像John Resig的解决方案那样复杂的东西,只是(希望)一些一两行代码。
当前回答
我的一句话解决方案:
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
其他回答
如果你需要一个语法正确的答案:
这个答案考虑了介词,如“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');
});
});
请注意,我从提供的字符串中删除了相当多的特殊字符。您将需要调整正则表达式以满足项目的需求。
可以将第一个字符大写,并与其余字符串连接。
Let STR = 'john smith'; Let res = str.split(" "); res.forEach((w, index) => { res[index] = w. charat (0). touppercase ().concat(w。片(1,w.length)) }); Res = Res .join(" "); console.log (res);
与其他答案相比,我更喜欢下面的答案。它只匹配每个单词的第一个字母,并将其大写。更简单的代码,更容易阅读和更少的字节。它保留了现有的大写字母,以防止扭曲的首字母缩写。然而,你总是可以首先在你的字符串上调用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() });
}
例子: String.prototype.toTitle = function() { return this.replace(/(^|\s)\ s /g, function(t) {return t. touppercase ()}); } console.log('全部小写->','全部小写'.toTitle()); console.log('所有大写字母->','所有大写字母'.toTitle()); console.log("I'm a little teapot ->","I'm a little teapot".toTitle());
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();
}
}
将单个单词转换为标题大小写的简单方法
使用“切片”方法和字符串拼接
str.slice(0, 1).toUpperCase() + str.slice(1, str.length)
*如果你想要小写单词的其余部分,在结尾添加.toLowerCase()
使用ES6扩展操作符、映射和Join
[...str].map((w, i) => i === 0 ? w[0].toUpperCase() : w).join('')
推荐文章
- 使用jQuery以像素为整数填充或边距值
- 检查是否选择了jQuery选项,如果没有选择默认值
- Next.js React应用中没有定义Window
- 如何重置笑话模拟函数调用计数之前,每次测试
- 如何强制一个功能React组件渲染?
- 在javascript中从平面数组构建树数组
- 将Dropzone.js与其他字段集成到现有的HTML表单中
- 如何在AngularJS中观察路由变化?
- JavaScript DOM删除元素
- 将dd-mm-yyyy字符串转换为日期
- Javascript复选框onChange
- Javascript函数前导bang !语法
- 如何在页面上遍历所有DOM元素?
- 在JS/jQuery中触发按键/按键/按键事件?
- 如何每5秒重新加载页面?