是否有一个简单的方法来转换字符串标题大小写?例如,约翰·史密斯变成了约翰·史密斯。我不是在寻找像John Resig的解决方案那样复杂的东西,只是(希望)一些一两行代码。
当前回答
有一些很好的答案,但是,许多人使用正则表达式来查找单词,但是,由于某种原因,没有人使用正则表达式来替换第一个字符。为了解释,我将提供一个较长的解决方案和一个较短的解决方案。
长期解决方案(更具解释性)。通过使用正则表达式[^\s_\-/]*,我们可以找到句子中的每一个单词。随后,我们可以使用正则表达式。与单词中的第一个字符匹配。使用正则表达式版本的replace来替换这两个函数,我们可以像这样更改解决方案:
function toUpperCase(str){返回str.toUpperCase();} 函数capitalizeWord(word){返回word.replace(/。/,包含);} 函数大写(句子){返回句子。tolowercase()。替换(/ [/ ^ \ s_ \] * / g, capitalizeWord);} console.log(大写(“hello world”));//输出:Hello World
对于做同样事情的单个函数,我们将replace调用嵌套如下:
函数大写(句子){ 返回sentence.toLowerCase()。替换(/[^\s_\-/]*/g, function (word) { 返回word.replace(/。/,函数(ch){返回ch. touppercase ();}); }); } console.log(大写(“hello world”));//输出:Hello World
其他回答
如果你需要一个语法正确的答案:
这个答案考虑了介词,如“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');
});
});
请注意,我从提供的字符串中删除了相当多的特殊字符。您将需要调整正则表达式以满足项目的需求。
约翰·史密斯->约翰·史密斯
'john smith'.replace(/(^\w|\s+\w){1}/g, function(str){ return str.toUpperCase() } );
我用正则表达式回答。
更多regex信息:https://regex101.com/r/AgRM3p/1
function toTitleCase(string = '') { const regex = /^[a-z]{0,1}|\s\w/gi; string = string.toLowerCase(); string.match(regex).forEach((char) => { string = string.replace(char, char.toUpperCase()); }); return string; } const input = document.getElementById('fullname'); const button = document.getElementById('button'); const result = document.getElementById('result'); button.addEventListener('click', () => { result.innerText = toTitleCase(input.value); }); <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Test</title> </head> <body> <input type="text" id="fullname"> <button id="button">click me</button> <p id="result">Result here</p> <script src="./index.js"></script> </body> </html>
我认为最简单的是使用css。
function format_str(str) {
str = str.toLowerCase();
return '<span style="text-transform: capitalize">'+ str +'</span>';
}
我的一句话解决方案:
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
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔