可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
What is wrong with this function? I am lost thanks for help.
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
for (var i = 0; i < splitStr.length; i++) {
if (splitStr.length[i] < splitStr.length) {
splitStr[i].charAt(0).toUpperCase();
}
str = splitStr.join(' ');
}
return str;
}
titleCase("I'm a little tea pot");
回答1:
You are not assigning your changes to the array again, so all your efforts are in vain. Try this:
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
for (var i = 0; i < splitStr.length; i++) {
// You do not need to check if i is larger than splitStr length, as your for does that for you
// Assign it back to the array
splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
}
// Directly return the joined string
return splitStr.join(' ');
}
document.write(titleCase("I'm a little tea pot"));
回答2:
You are making complex a very easy thing. You can add this in your CSS:
.capitalize {
text-transform: capitalize;
}
In javascript, you can add the class to an element
document.getElementById("element").className="capitalize";
回答3:
ES6 version:
const toTitleCase = (phrase) => {
return phrase
.toLowerCase()
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
};
let result = toTitleCase('maRy hAd a lIttLe LaMb');
console.log(result);
回答4:
If you can use thirdparty library then lodash has a helper function for you.
https://lodash.com/docs/4.17.3#startCase
_.startCase('foo bar');
// => 'Foo Bar'
_.startCase('--foo-bar--');
// => 'Foo Bar'
_.startCase('fooBar');
// => 'Foo Bar'
_.startCase('__FOO_BAR__');
// => 'FOO BAR'
<script src="https://cdn.jsdelivr.net/lodash/4.17.3/lodash.min.js"></script>
回答5:
ES2015 version:
const titleCase = title => title
.split(/ /g).map(word =>
`${word.substring(0,1).toUpperCase()}${word.substring(1)}`)
.join("");
回答6:
Also a good option (particularly if you're using freeCodeCamp):
function titleCase(str) {
var wordsArray = str.toLowerCase().split(/\s+/);
var upperCased = wordsArray.map(function(word) {
return word.charAt(0).toUpperCase() + word.substr(1);
});
return upperCased.join(" ");
}
回答7:
You could simply use a regular expression function to change the capitalization of each letter. With V8 JIST optimizations, this should prove to be the fastest and most memory efficient.
'tHe VeRy LOOong StRINg'.replace(/\b[a-z]|\B[A-Z]/g, function(x){return String.fromCharCode(x.charCodeAt(0)^32)})
Or, as a function:
var autoCaps = (function(){
var fromCharCode = String.fromCharCode;
return function(string){
string.replace(/\b[a-z]|\B[A-Z]/g, function(x){
return fromCharCode(x.charCodeAt(0)^32);
});
}
})();
Demo
<input id="input" type="text" value="'tHe VeRy LOOong StRINg'" /><br /><br />
<input id="output" type="text" readonly />
<script>
(function(){
var fromCharCode = String.fromCharCode;
(input.oninput = function(){
output.value = input.value.replace(
/\b[a-z]|\B[A-Z]/g,
function(x){return fromCharCode(x.charCodeAt(0)^32)}
);
})();
})();
</script>
回答8:
This routine will handle hyphenated words and words with apostrophe.
function titleCase(txt) {
var firstLtr = 0;
for (var i = 0;i < text.length;i++){
if (i == 0 &&/[a-zA-Z]/.test(text.charAt(i))) firstLtr = 2;
if (firstLtr == 0 &&/[a-zA-Z]/.test(text.charAt(i))) firstLtr = 2;
if (firstLtr == 1 &&/[^a-zA-Z]/.test(text.charAt(i))){
if (text.charAt(i) == "'"){
if (i + 2 == text.length &&/[a-zA-Z]/.test(text.charAt(i + 1))) firstLtr = 3;
else if (i + 2 < text.length &&/[^a-zA-Z]/.test(text.charAt(i + 2))) firstLtr = 3;
}
if (firstLtr == 3) firstLtr = 1;
else firstLtr = 0;
}
if (firstLtr == 2){
firstLtr = 1;
text = text.substr(0, i) + text.charAt(i).toUpperCase() + text.substr(i + 1);
}
else {
text = text.substr(0, i) + text.charAt(i).toLowerCase() + text.substr(i + 1);
}
}
}
titleCase("pAt o'Neil's");
// returns "Pat O'Neil's";
回答9:
function titleCase(str) {
var myString = str.toLowerCase().split(' ');
for (var i = 0; i < myString.length; i++) {
var subString = myString[i].split('');
for (var j = 0; j < subString.length; j++) {
subString[0] = subString[0].toUpperCase();
}
myString[i] = subString.join('');
}
return myString.join(' '); }
回答10:
Raw code:
function capi(str) {
var s2 = str.trim().toLowerCase().split(' ');
var s3 = [];
s2.forEach(function(elem, i) {
s3.push(elem.charAt(0).toUpperCase().concat(elem.substring(1)));
});
return s3.join(' ');
}
capi('js string exasd');
回答11:
Or can be done using replace(), and replace each word's first letter with its "upperCase".
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(word) {
return word.replace(word[0], word[0].toUpperCase());
}).join(' ');
}
titleCase("I'm a little tea pot");
回答12:
I usually prefer not to use regexp because of readability and also I try to stay away from loops. I think this is kind of readable.
function capitalizeFirstLetter(string) {
return string && string.charAt(0).toUpperCase() + string.substring(1);
};
回答13:
/* 1. Transform your string into lower case
2. Split your string into an array. Notice the white space i'm using for separator
3. Iterate the new array, and assign the current iteration value (array[c]) a new formatted string:
- With the sentence: array[c][0].toUpperCase() the first letter of the string converts to upper case.
- With the sentence: array[c].substring(1) we get the rest of the string (from the second letter index to the last one).
- The "add" (+) character is for concatenate both strings.
4. return array.join(' ') // returns the formatted array like a new string.*/
function titleCase(str){
str = str.toLowerCase();
var array = str.split(' ');
for(var c = 0; c < array.length; c++){
array[c] = array[c][0].toUpperCase() + array[c].substring(1);
}
return array.join(' ');
}
titleCase("I'm a little tea pot");
回答14:
Used replace()
with RegExp
function titleCase(str) {
var newStr = str.toLowerCase().replace(/./, (x) => x.toUpperCase()).replace(/[^']\b\w/g, (y) => y.toUpperCase());
console.log(newStr);
}
titleCase("I'm a little tea pot")
回答15:
Please check the code below.
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
var nstr = "";
for (var i = 0; i < splitStr.length; i++) {
nstr += (splitStr[i].charAt(0).toUpperCase()+ splitStr[i].slice(1) + "
");
}
console.log(nstr);
}
var strng = "this is a new demo for checking the string";
titleCase(strng);
回答16:
A more compact (and modern) rewrite of @somethingthere's proposed solution:
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(chunk){
return chunk.charAt(0).toUpperCase() + chunk.substring(1);
}).join(' ');
}
document.write(titleCase("I'm an even smaller tea pot"));
回答17:
As of ECMA2017 or ES8
const titleCase = (string) => {
return string
.split(' ')
.map(word => word.substr(0,1).toUpperCase() + word.substr(1,word.length))
.join(' ');
};
let result = titleCase('test test test');
console.log(result);
Explanation:
1. First, we pass the string "test test test" to our function "titleCase".
2. We split a string on the space basis so the result of first function "split" will be ["test","test","test"]
3. As we got an array, we used map function for manipulation each word in the array. We capitalize the first character and add remaining character to it.
4. In the last, we join the array using space as we split the string by sapce.
回答18:
Here's how you could do it with the map
function basically, it does the same as the accepted answer but without the for-loop
. Hence, saves you few lines of code.
function titleCase(text) {
if (!text) return text;
if (typeof text !== 'string') throw "invalid argument";
return text.toLowerCase().split(' ').map(value => {
return value.charAt(0).toUpperCase() + value.substring(1);
}).join(' ');
}
console.log(titleCase("I'm A little tea pot"));
回答19:
isn't it better to make whole string a lowerCase and only first letter of it upper?
function titleCase(str) {
return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase();
}