Title case a sentence without split


#1

how can i title case a sentence without split


#2

For what reason? Why not use a simple and direct method? The advantage of the split is that it makes it easy to find the first letter of each word.

I guess if you really wanted, you could loop through each character in a string. You will push each character onto and array. If it is the first character in a string or the previous char was a space, you make it uppercase, if not make it lowercase. Then you join that array.

It would work. I suppose it might be a little more efficient (maybe), but on a modern computer it won’t make enough of a difference to justify the loss in simplicity and clarity of a split method.


#3

Or use a regex, which should net the shortest solution.


#4

then why there is error when i write:

var str1=str.split("").touppercase();


#5

sir i dont know what is regex??


#6

Regular expressions — but nevermind then. If the reason you don’t want to use split is just because of an error, that’s no reason to abandon it. Drill down, look at the error message and fix it. The line you wrote is wrong both for the test cases and in general, since there is no touppercase function.


#7
  • touppercase() isn’t the name of the method, it’s toUpperCase().
  • split splits a string into an array of strings. Arrays do not have a toUpperCase() method, so it won’t work even if you fix the method name.
  • Strings are immutable in JavaScript (as with most other languages that handle strings in a sane manner). That’s why you generally titlecase by copying the first letter, uppercasing it, then joining it onto a copy of the rest of the word.

#8

You could do something like this

let test = "test";
let test2 = test[0].toUpperCase() + test.slice(1)
console.log(test2)

// logs "Test"

#9

I assume this is for a JS challenge, otherwise you could use css, like so:

text-transform: capitalize;


#10

Yeah, I assume it’s for the algorithm challenge “title case a sentence”, so has to be JS. And just text-transform: uppercase won’t work, it ends up being more complex that just JS; you would need to split into words, wrap each word in a tag (with say a class of word), then use .word::first-letter { text-transform: uppercase }


#11

text-transform: capitalize; transforms the first letter of each word.


#12

without giving the solution I’ll sugggest you use a general problem-solving approach like what I outline here

so I’d write the first test case on paper

input:   I'm a little tea pot
target:  I'm A Little Tea Pot

try to describe in everyday language - without using programming terms like variables, arrays, loops, functions etc - how to get the target from the input

since you don’t want to use split the goal is to come up with a solution that does not split the input string into an array - or in everyday language avoids an intermediate step of rewriting the sentence into a sequence of separated words

if you struggle to understand the problem or come up with a solution try to break up the problem into smaller problems that are more manageable

how are problems broken up? what does a smaller problem mean? there can be many answers in general

a problem can be made smaller in size - e.g. consider an array of 10 items or 1 item instead of an array of 1000 items

a problem can be made smaller in scope - e.g. solve for just English or just Latin languages instead of all languages of the world

a problem can be broken up into multiple sub-problems - the solution to a sub-problem becomes a step in the solution of the original problem


#14

Ha, sorry, I read your post as text-transform: uppercase, not capitalize


#15
function titleCase(str) {
 str = str.split(' ');
//to make the row element in loop as sentences can be infinite
  for (i = 0; i < str.length; i++) {
    str[i] = str[i].toLowerCase().split('');
    
    //spliting lower case of each element an array's zeroth elment capital..
    str[i][0] = str[i][0].toUpperCase();
    str[i] = str[i].join('');
  }

  return str.join(' ');
}

titleCase("I'm a little tea pot");

is this correct or any error in this???


#16

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#17

Your final solution still uses split, which I thought you wanted to avoid. If you really do not want to use split, you could do the following:

function titleCase(str) {
   var newStr = '';
   for (var i in str) {
     newStr += str[i-1] === ' ' || i==0 ? str[i].toUpperCase() : str[i].toLowerCase()
   }
   return newStr;
}

or using a regular expression (as @lynxlynxlynx suggested):

function titleCase(str) {
 return str.toLowerCase().replace(/\S+/g, function(word) {
   return word[0].toUpperCase()+word.slice(1);
 }); 
}

#18

Well that regex just reinvents split(). For it to be worthy of mentioning, everything should be done with them. Unfortunately javascript doesn’t support any modifiers (wtf), so you still have to use a function:

"a aDF SDFD -.sdf-a s".toLowerCase().replace(/(\s)(\S)/g, (match, space, capital) => space+capital.toUpperCase())
"a Adf Sdfd -.sdf-a S"

#19

I also had this regex version:

function titleCase(str) {
  return str.toLowerCase()
    .replace(/^(.)|[^\w-'](\w)/gi, match => match.toUpperCase());
}

#20

Nice trick, whitespace doesn’t know case. :slight_smile: