有没有一种简单的方法将字符串转换为标题格式?例如,john smith
变成 John Smith
。我不想要像John Resig的解决方案那样复杂的东西,只是(希望)一种一两行代码就能实现的方法。
有没有一种简单的方法将字符串转换为标题格式?例如,john smith
变成 John Smith
。我不想要像John Resig的解决方案那样复杂的东西,只是(希望)一种一两行代码就能实现的方法。
John Smith -> 约翰·史密斯
'john smith'.replace(/(^\w|\s+\w){1}/g, function(str){ return str.toUpperCase() } );
import { words, lowerCase, capitalize, endsWith, padEnd } from 'lodash';
const titleCase = string =>
padEnd(
words(string, /[^ ]+/g)
.map(lowerCase)
.map(capitalize)
.join(' '),
string.length,
);
_.startCase('john smith');
呢?https://lodash.com/docs/4.17.15#startCase - w3debugger_.startCase('john-smith') => John Smith
。但是,如果整个字符串都是大写的,并且您只想将第一个字符大写,那么startCase就无法帮助您了。例如:_.startCase('JOHN SMITH') => JOHN SMITH
。 - Avinash_.startCase('HELLO'.toLowerCase())
吗? - w3debuggerString.prototype.capitalize = function() {
return this.toLowerCase().split(' ').map(capFirst).join(' ');
function capFirst(str) {
return str.length === 0 ? str : str[0].toUpperCase() + str.substr(1);
}
}
使用方法:
"hello world".capitalize()
String.prototype
部分以外都很好。不要搞乱内置对象! - Travis Webbfunction titleCase(str) {
str = str.toLowerCase();
var strArray = str.split(" ");
for(var i = 0; i < strArray.length; i++){
strArray[i] = strArray[i].charAt(0).toUpperCase() + strArray[i].substr(1);
}
var result = strArray.join(" ");
//Return the string
return result;
}
这个解决方案考虑了标点符号来划分新的句子,处理引用,将小写字母转换为小写,并忽略缩写词或全大写单词。
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 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
}
Implementation version
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 toTitleCase(input){ return input.....join(' ') }
呢? - mplungjan又是另一个版本加入到混合中。这也会检查字符串长度是否为0:
String.prototype.toTitleCase = function() {
var str = this;
if(!str.length) {
return "";
}
str = str.split(" ");
for(var i = 0; i < str.length; i++) {
str[i] = str[i].charAt(0).toUpperCase() + (str[i].substr(1).length ? str[i].substr(1) : '');
}
return (str.length ? str.join(" ") : str);
};
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 toTitleCase(text) {
return text.toLowerCase().replace(
/(?<!\S)\S/ug, match => match.toUpperCase()
);
}
toTitleCase('don’t perform input–output ’til out-of-memory');
// 'Don’t Perform Input–output ’til Out-of-memory'
\s
和不是\p{Pd}
,即[^\s\p{Pd}]
)的单词字符的实现:function toTitleCase(text) {
return text.toLowerCase().replace(
/(?<![^\s\p{Pd}])[^\s\p{Pd}]/ug, match => match.toUpperCase()
);
}
toTitleCase('don’t perform input–output ’til out-of-memory');
// 'Don’t Perform Input–Output ’til Out-Of-Memory'
'DŽungla'
。你期望得到什么? - undefinedvar stringToConvert = 'john';
stringToConvert = stringToConvert.charAt(0).toUpperCase() + Array.prototype.slice.call(stringToConvert, 1).join('');
console.log(stringToConvert);