/**
* @param String str The text to be converted to titleCase.
* @param Array glue the words to leave in lowercase.
*/
var titleCase = function(str, glue){
glue = (glue) ? glue : ['of', 'for', 'and'];
return str.replace(/(\w)(\w*)/g, function(_, i, r){
var j = i.toUpperCase() + (r != null ? r : "");
return (glue.indexOf(j.toLowerCase())<0)?j:j.toLowerCase();
});
};
希望这对你有帮助。
编辑
如果你想处理前导粘合词,你可以跟踪这个w/一个变量:
var titleCase = function(str, glue){
glue = !!glue ? glue : ['of', 'for', 'and', 'a'];
var first = true;
return str.replace(/(\w)(\w*)/g, function(_, i, r) {
var j = i.toUpperCase() + (r != null ? r : '').toLowerCase();
var result = ((glue.indexOf(j.toLowerCase()) < 0) || first) ? j : j.toLowerCase();
first = false;
return result;
});
};
String.prototype.toTitleCase = function() {
var i, j, str, lowers, uppers;
str = this.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
// Certain minor words should be left lowercase unless
// they are the first or last words in the string
lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At',
'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
for (i = 0, j = lowers.length; i < j; i++)
str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'),
function(txt) {
return txt.toLowerCase();
});
// Certain words such as initialisms or acronyms should be left uppercase
uppers = ['Id', 'Tv'];
for (i = 0, j = uppers.length; i < j; i++)
str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'),
uppers[i].toUpperCase());
return str;
}
例如:
"TO LOGIN TO THIS SITE and watch tv, please enter a valid id:".toTitleCase();
// Returns: "To Login to This Site and Watch TV, Please Enter a Valid ID:"
String.prototype.toProperCase = function() {
var words = this.split(' ');
var results = [];
for (var i = 0; i < words.length; i++) {
var letter = words[i].charAt(0).toUpperCase();
results.push(letter + words[i].slice(1));
}
return results.join(' ');
};
console.log(
'john smith'.toProperCase()
)
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..." ) );
var myPoem = 'What is a jQuery but a misunderstood object?'
//What is a jQuery but a misunderstood object? --> What Is A JQuery But A Misunderstood Object?
//code here
var capitalize = function(str) {
var strArr = str.split(' ');
var newArr = [];
for (var i = 0; i < strArr.length; i++) {
newArr.push(strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1))
};
return newArr.join(' ')
}
var fixedPoem = capitalize(myPoem);
alert(fixedPoem);
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");
function titlecase(str){
var arr=[];
var str1=str.split(' ');
for (var i = 0; i < str1.length; i++) {
var upper= str1[i].charAt(0).toUpperCase()+ str1[i].substr(1);
arr.push(upper);
};
return arr.join(' ');
}
titlecase('my name is suryatapa roy');
function toTitleCase(str) {
return str.replace(/\S+/g, str => str.charAt(0).toUpperCase() + str.substr(1).toLowerCase());
}
console.log(toTitleCase("a city named örebro")); // A City Named Örebro
function toTitleCase(input){
let output = input
.split(' ') // 'HOw aRe YOU' => ['HOw' 'aRe' 'YOU']
.map((letter) => {
let firstLetter = letter[0].toUpperCase() // H , a , Y => H , A , Y
let restLetters = letter.substring(1).toLowerCase() // Ow, Re, OU => ow, re, ou
return firstLetter + restLetters // conbine together
})
.join(' ') //['How' 'Are' 'You'] => 'How Are You'
return output
}
实现版本
function toTitleCase(input){
return input
.split(' ')
.map(i => i[0].toUpperCase() + i.substring(1).toLowerCase())
.join(' ')
}
toTitleCase('HoW ARe yoU') // reuturn 'How Are You'
function titleCase(str)
{
var words = str.split(" ");
for ( var i = 0; i < words.length; i++ )
{
var j = words[i].charAt(0).toUpperCase();
words[i] = j + words[i].substr(1);
}
return words.join(" ");
}
var stopWordsArray = new Array("a", "all", "am", "an", "and", "any", "are", "as", "at", "be", "but", "by", "can", "can't", "did", "didn't", "do", "does", "doesn't", "don't", "else", "for", "get", "gets", "go", "got", "had", "has", "he", "he's", "her", "here", "hers", "hi", "him", "his", "how", "i'd", "i'll", "i'm", "i've", "if", "in", "is", "isn't", "it", "it's", "its", "let", "let's", "may", "me", "my", "no", "of", "off", "on", "our", "ours", "she", "so", "than", "that", "that's", "thats", "the", "their", "theirs", "them", "then", "there", "there's", "these", "they", "they'd", "they'll", "they're", "they've", "this", "those", "to", "too", "try", "until", "us", "want", "wants", "was", "wasn't", "we", "we'd", "we'll", "we're", "we've", "well", "went", "were", "weren't", "what", "what's", "when", "where", "which", "who", "who's", "whose", "why", "will", "with", "won't", "would", "yes", "yet", "you", "you'd", "you'll", "you're", "you've", "your");
// Only significant words are transformed. Handles acronyms and punctuation
String.prototype.toTitleCase = function() {
var newSentence = true;
return this.split(/\s+/).map(function(word) {
if (word == "") { return; }
var canCapitalise = true;
// Get the pos of the first alpha char (word might start with " or ')
var firstAlphaCharPos = word.search(/\w/);
// Check for uppercase char that is not the first char (might be acronym or all caps)
if (word.search(/[A-Z]/) > 0) {
canCapitalise = false;
} else if (stopWordsArray.indexOf(word) != -1) {
// Is a stop word and not a new sentence
word.toLowerCase();
if (!newSentence) {
canCapitalise = false;
}
}
// Is this the last word in a sentence?
newSentence = (word.search(/[\.!\?:]['"]?$/) > 0)? true : false;
return (canCapitalise)? word.replace(word[firstAlphaCharPos], word[firstAlphaCharPos].toUpperCase()) : word;
}).join(' ');
}
// Pass a string using dot notation:
alert("A critical examination of Plato's view of the human nature".toTitleCase());
var str = "Ten years on: a study into the effectiveness of NCEA in New Zealand schools";
str.toTitleCase());
str = "\"Where to from here?\" the effectivness of eLearning in childhood education";
alert(str.toTitleCase());
/* Result:
A Critical Examination of Plato's View of the Human Nature.
Ten Years On: A Study Into the Effectiveness of NCEA in New Zealand Schools.
"Where to From Here?" The Effectivness of eLearning in Childhood Education. */
function titleCase(str) {
str = str.toLowerCase(); //ensure the HeLlo will become Hello at the end
var words = str.split(" ");
var capitalized = words.map(function(word) {
return word.charAt(0).toUpperCase() + word.substring(1, word.length);
});
return capitalized.join(" ");
}
console.log(titleCase("I'm a little tea pot"));
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');
});
});
function capitalize(str) {
const word = [];
for (let char of str.split(' ')) {
word.push(char[0].toUpperCase() + char.slice(1))
}
return word.join(' ');
}
console.log(capitalize("this is a test"));
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.'));
const textString = "Convert string to title case with Javascript.";
const converted = textString.replace(/\b[a-zA-Z]/g, (match) => match.toUpperCase());
console.log(converted)
function titleize(str) {
let upper = true
let newStr = ""
for (let i = 0, l = str.length; i < l; i++) {
// Note that you can also check for all kinds of spaces with
// str[i].match(/\s/)
if (str[i] == " ") {
upper = true
newStr += str[i]
continue
}
newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase()
upper = false
}
return newStr
}
// NOTE: you could beat that using charcode and string builder I guess.
str = "the QUICK BrOWn Fox jUMPS oVeR the LAzy doG";
function regex(str) {
return str.replace(
/\w\S*/g,
function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}
);
}
function split(str) {
return str.
split(' ').
map(w => w[0].toUpperCase() + w.substr(1).toLowerCase()).
join(' ');
}
function complete(str) {
var i, j, str, lowers, uppers;
str = str.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
// Certain minor words should be left lowercase unless
// they are the first or last words in the string
lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At',
'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
for (i = 0, j = lowers.length; i < j; i++)
str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'),
function(txt) {
return txt.toLowerCase();
});
// Certain words such as initialisms or acronyms should be left uppercase
uppers = ['Id', 'Tv'];
for (i = 0, j = uppers.length; i < j; i++)
str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'),
uppers[i].toUpperCase());
return str;
}
function firstLetterOnly(str) {
return str.replace(/\b(\S)/g, function(t) { return t.toUpperCase(); });
}
function forLoop(str) {
let upper = true;
let newStr = "";
for (let i = 0, l = str.length; i < l; i++) {
if (str[i] == " ") {
upper = true;
newStr += " ";
continue;
}
newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase();
upper = false;
}
return newStr;
}