This question already has answers here:
Convert string to Title Case with JavaScript
(68 answers)
Closed 7 years ago.
So, I want to convert a string into a Title Case string. I've written this code but I get the same string in lowercase when I run this. Could anyone please point out where I'm wrong with this? Any help is much appreciated.
function capitalize(str) {
return str.toUpperCase();
}
function titleCase(str1) {
str1 = str1.toLowerCase();
var arr = str1.split(' ');
var l = arr.length;
var m;
for (var i = 0; i < l; i++) {
m = arr[i].length;
for (var j = 0; j < m; j++) {
if (j === 0) {
arr[i][0] = capitalize(arr[i][0]);
}
else {
arr[i][j] = arr[i][j];
}
}
}
return arr;
}
titleCase("I'm a little tea potty");
I'm pretty sure you were given advice on exactly this question earlier, but using ES5 methods (you can downgrade it to for loops yourself).
function titleCase(str1) {
return str1.toLowerCase().split(' ').map(function(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}).join(' ');
}
document.body.textContent = titleCase("I'm a little tea potty");
<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.4.1/es5-shim.min.js"></script>
Now, what's with your code?
function capitalize(str) {
return str.toUpperCase();
}
function titleCase(str1) {
str1 = str1.toLowerCase();
var arr = str1.split(' ');
var l = arr.length;
var m;
for (var i = 0; i < l; i++) {
m = arr[i].length;
for (var j = 0; j < m; j++) {
if (j === 0) {
arr[i][0] = capitalize(arr[i][0]);
} else {
arr[i][j] = arr[i][j];
}
}
}
return arr;
}
document.body.textContent = titleCase("I'm a little tea potty");
Let's look at it bit by bit:
function capitalize(str) {
return str.toUpperCase();
}
Nothing wrong with the above, except that it seems pretty pointless to functionalise.
So, now we have your function, you take an argument (a string) and then you make it all lower cased
function titleCase(str1) {
str1 = str1.toLowerCase();
So here comes your string "I'm a little tea potty" and it becomes "i'm a little tea potty". So far so good. Then you split it at spaces.
var arr = str1.split(' ');
var l = arr.length;
var m;
Along comes your string and becomes var arr = ["i'm","a","little","tea","potty"]; and l becomes 5, the length of this array.
Next you intend to loop through the array arr, that looks fine
for (var i = 0; i < l; i++) {
So for each word (a string) in the array (iteration) you get the length of the string, the first i'm is 3.
m = arr[i].length;
Then you intend to iterate each character in the word, which is fine
for (var j = 0; j < m; j++) {
Then, you are saying if it is the first character of the word then I want a capital letter, otherwise do nothing with it.
if (j === 0) {
arr[i][0] = capitalize(arr[i][0]);
} else {
arr[i][j] = arr[i][j];
}
But here's the problem, you try to write the characters back to the string, which is immutable. No errors are thrown, just nothing changes, it's like the string has a read-only switch, just like on a memory card. So your loops continue on and on, do nothing, until all is done. Then you return the array.
return arr;
And surpirise, it is just the same as when you split the sentence into words. ["i'm","a","little","tea","potty"]
I have changed your code. This will help you ..
function capitalize(str) {
return str.toUpperCase();
}
function titleCase(str1) {
str1 = str1.toLowerCase();
var arr = str1.split(' ');
var l = arr.length;
var m;
for (var i = 0; i < l; i++) {
m = arr[i].length;
arr[i] = capitalize(arr[i][0])+arr[i].substr(1);
}
return arr;
}
titleCase("I'm a little tea potty");
One liner here
function titleCase(str) {
return str.split(' ').map(function(s){
return s.slice(0, 1).toUpperCase() + s.slice(1);
}).join(' ');
}
titleCase("I'm a little tea potty");
Related
First of all, I would like to apologize in case my title is not concise as it should be, but my point is, if you take a look at the following code which is selection sort algorithm, it's obvious for someone to analyze its complexity.
module.exports = function (arr) {
var temp;
for (var i = 0; i < arr.length; i++) {
var iTh = i;
for (var j = i+1; j < arr.length; j++) {
if (arr[j] < arr[iTh]) {
iTh = j;
}
}
temp = arr[i];
arr[i] = arr[iTh];
arr[iTh] = temp;
}
return arr;
}
But what if an algorithm contains hidden loops which are provided by particular language's functions or methods. For instance these two functions are both reversing a string, and they have JavaScript methods which have complexity behind them too.
So! How can someone analyze the complexity of these two and pick the optimal one? Or they don't qualify to be algorithms?
First Reverse
exports.reverse1 = function (str) {
if (str == undefined || str.length) {
return 0;
}
let collector = [];
for (var i = str.length; i >= 0; i--) {
collector.push(str.charAt(i));
}
return collector.join("");
}
Second Reverse
exports.reverse2 = function (str) {
if (str == undefined || str === "") {
return 0;
}
return str.split("").reverse().join("");
}
Okay so palindrome is a word that is the same spelled backwards. What if we want to take a phrase that is also the same backwards? So kook is one. race car is another one.
So I made one that doesn't account for spaces.
function isPal(string){
var l = string.length;
for (var i = 0; i < (l/2); ++i) {
if (string.charAt(i) != string.charAt(l - i - 1)){
return false;
}
}
return true;
}
This one works fine for words.
Now I'm thinking, push the string into an array, and split up each character into it's own string, then remove any spaces, and then run if (string.charAt(i) != string.charAt(string.length - i - 1)). So here's what I wrote but failed at..
function isPalindrome(string){
var arr = [];
arr.push(string.split(''));
for (i = 0; i < arr.length; i++){
if (arr[i] === ' '){
arr.splice(i, 1);
if I return arr, it still gives me the string with the space in it. How do I accomplish this? Thanks!
EDIT: Used the solution but still getting false on 'race car'
Here's what I got:
function isPalindrome(string){
var arr = string.split('');
for (i = 0; i < arr.length; i++){
if (arr[i] === ' '){
arr.splice(i, 1);
} else if (arr[i] != arr[arr.length - i - 1]){
return false;
}
}
return true;
}
where's my error?
Your problem is in the following line:
arr.push(string.split(''));
string.split('') returns an array. So, arr is actually an array with one entry it in (another array that contains your characters). Replace:
var arr = [];
arr.push(string.split(''));
with
var arr = string.split('');
and it should work as expected
Just check check the string without spaces:
function isPal(string){
string = string.split(" ").join(""); // remove all spaces
var l = string.length;
for (var i = 0; i < (l/2); ++i) {
if (string.charAt(i) != string.charAt(l - i - 1)){
return false;
}
}
return true;
}
isPal("a man a plan a canal panama"); // true
It seems much easier to just split into an array, reverse and join again to check if a word is a palindrome. If you want to ignore spaces, just remove all instances of spaces:
let word = 'race car';
let isPalindrome = (word) => {
let nospaces = word.replace(/\s/g, '');
return [...nospaces].reverse().join('') === nospaces;
}
Or non-es6:
var word = 'race car';
var isPalindrome = function(word) {
var nospaces = word.replace(/\s/g, '');
return nospaces.split('').reverse().join('') === nospaces;
}
How can I make individual characters within a string repeat a given amount of times?
That is, how do I turn "XyZ" into "XXXyyyZZZ"?
Try this:
var foo = 'bar';
function makeString(str, repeat) {
var str = Array.prototype.map.call(str, function(character) {
var nascentStr = '';
while (nascentStr.length < repeat) {
nascentStr += character;
}
return nascentStr;
}).join('');
return str;
}
alert(makeString(foo, 3));
You'll need to use a combination of a few functions. First you'll need to split the string into individual characters:
var charArray = "XyZ".split('');
Once you have it split up, you can use a combination of the .map function and a nifty little trick of javascript Array.
var someMultiplier = 5;
var duplicatedArray = charArray.map(function(char) {
return Array(someMultiplier).join(char);
});
At that point, you have an array of strings that have the duplicate letters, and you can combine them back with .join
var dupString = duplicatedArray.join('');
dupString === "XXXXXyyyyyZZZZZ
Sounds straight forward. You can run this in your browser's console:
var my = 'XyZ';
function repeat(str, times) {
var res = '';
for (var i in str) {
var char = str[i];
for (var j=0; j < times; j++) {
res += char;
}
}
return res;
}
var his = repeat(my, 3);
console.log(his);
you have not mentioned what will happen if input will be like xyxzy. Assuming it will be xxxyyxxxzzzyyy
// function takes input string & num of repitation
function buildString(input, num) {
var _currentChar = ""; // Final output string
for (var m = 0; m < input.length; m++) {
//call another function which will return XXX or yyy or zzz & then finally concat it
_currentChar += _repeatString((input.charAt(m)), num);
}
}
// It will return XXX or yyy or ZZZ
// takes individual char as input and num of times to repeat
function _repeatString(char, num) {
var _r = "";
for (var o = 0; o < num; o++) {
_r += char;
}
return _r
}
buildString('XyZ', 3)
jsfiddle for Example
function repeatStringNumTimes(str, num) {
let valueCopy = str
if (num > 0) {
for (var i = 0; i < num - 1; i++) {
valueCopy = valueCopy.concat(str)
}
} else {
valueCopy = ""
}
return valueCopy;
}
repeatStringNumTimes("abc", 3);
These days can be done a lot easier:
const repeater = (str, n) => [...str].map(c => c.repeat(n)).join('');
alert(repeater('XyZ', 3));
My code was work well with string like "The quick brown fox jumped over the lazy dog".
But not work with string like "Google do a barrel roll".
It says problem is "TypeError undefined is not an object(evaluating 'Astr[i].length') ".
function findLongestWord(str) {
var Astr = str.split(" ");
var t = Astr[0].length;
var Al = Astr.length;
var j = 0;
for(var i =1; i < t;i++)
{
if(t < Astr[i].length)
{
t = Astr[i].length;
j = i;
}
}
str = Astr[j];
return str.length;
}
findLongestWord("Google do a barrel roll");
Here is one way of improving your function:
var str = 'Google do a barrel roll';
function findLongestWord(str) {
var Astr = str.split(' ');
if (!Astr.length) {
throw new Error('findLongestWord(): no words in str');
}
var t = Astr[0].length;
var Al = Astr.length;
var j = 0;
for(var i = 0; i < Al; i++)
{
if(t < Astr[i].length)
{
t = Astr[i].length;
j = i;
}
}
str = Astr[j];
return str.length;
}
findLongestWord(str);
//=> 6
You can also do something like this (which is a little easier to understand):
str.split(' ').reduce(function(longest, cur) {
return (cur.length > longest.length) ? cur : longest;
}, '');
//=> Google
you have problem with the variables in your 'for' loop.
As you can see, you split the array and get the length of the first member in the array
So basicly you get the first word length instead of the word count
var Astr = str.split(" ");
var t = Astr[0].length;
Here you can see that you use 't' (the first word length) as your loop bounds.
for(var i =1; i < t;i++)
Keep your code simple & readable this way it will be maintainable.
function findLongestWord(str) {
var words = str.split(" ");
var words_count = words.length;
var longest_word_length = 0;
for(var i = 0; i < words_count; i++){
if(longest_word_length < words[i].length){
longest_word_length = words[i].length;
}
}
return longest_word_length;
}
findLongestWord("Google do a barrel roll");
Note that you always can use short-hand functions for that
function findLongestWord(str) {
return str.split(' ').reduce(function(longest, cur) {
return (cur.length > longest.length) ? cur : longest;
}, '').length;
}
findLongestWord("Google do a barrel roll");
function findLongestWord(str)
{var arr=[];
arr=str.split(' ');
arr=arr.sort(function(a,b)
{
return b.length-a.length; /*sorting the array in decending order of
lengths of each word*/
});
var st=arr[0]; /* obviously the first element of the array will
have longest length.*/
return st.length;
}
findLongestWord("Google do a barrel roll");
I wrote this function to log a new string from the given string where the letters should be the following one in the alphabet and all of the vowels would be uppercase.
Now I have the issue of not being able to split the string the way I want it. Right now the words are being split into separate characters in an array when I'd really like the string to be split on the white spaces. Could anybody explain why this is happening?
And when I put a space between the "" in the split method I just get all the characters and "undefined" where the white spaces should be. Thanks for your help!
function replace(str) {
var newStr = [];
var vowels = 'aeiou';
var alpha = [ 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
];
str = str.split("");
newStr.length = str.length;
for(var i = 0; i < alpha.length; i++) {
for(var j = 0; j < str.length; j++) {
if(alpha[i] === str[j]) {
newStr[j] = (alpha[i + 1]);
}
}
}
for(var k = 0; k < vowels.length; k++) {
for(var x =0; x < newStr.length; x++){
if(vowels[k] === newStr[x]) {
newStr[x] = vowels[k].toUpperCase("");
}
}
}
return newStr;
}
console.log(replace("today is great"));
str = str.split(" ");
This splits your string up into ["today", "is", "great"].
When you get to
if(alpha[i] === str[j]) {
you never get inside the if block because you are comparing "a" to "today" or "a" to "is", etc. You'll need to break your string up even more to get this done I think.
I propose something like:
function replace(str) {
var alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'],
vowels = 'aeiou',
newStr = [],
i, j, k;
// split everything into words
str = str.split(' ');
for (i = 0; i < str.length; i++) {
// split everything into letters
str[i] = str[i].split('');
// make sure newStr has a similarly construction to str
newStr[i] = [];
for (j = 0; j < str[i].length; j++) {
for (k = 0; k < alpha.length; k++) {
if (alpha[k] === str[i][j]) {
// subsitute each letter
newStr[i][j] = alpha[k + 1];
}
}
}
}
for (i = 0; i < newStr.length; i++) {
// join newStr up to be an array of words instead of an array of an array of letters
newStr[i] = newStr[i].join('');
for (k = 0; k < vowels.length; k++) {
// replace each vowel with the uppercase version
newStr[i] = newStr[i].replace(vowels[k], vowels[k].toUpperCase());
}
}
return newStr;
}
If you actually want to see "UpEbz jt hsfbU" instead of ["UpEbz", "jt", "hsfbU"], just change return newStr to return newStr.join(' ');
To split string on whitespace try:
str = str.split(/\s+/);