-2

I want capitalize words in a string like...

Hello World, New York, First Name

...with JavaScript. But the trick is this I don't want to use any built-in JavaScript functions like toUpperCase, split, join, etc. I have made one sample program but got stuck.

var myString = "Hello world!";
var myArray = [];
var out= ""
for (var i=0; i < myString.length; i++){
    myArray.push(myString[i]);
    if(myString[i] == " "){
        continue;
    }
alert(myString[i])
}

This doesn't use split. I have converted my string in array and then I search for a blank array with continue.

Please don't recommend using CSS attributes such as text-transform:uppercase. I know all these. I want to do this with JavaScript only.

Chad Nouis
  • 6,861
  • 1
  • 27
  • 28
  • I have a little tool on my own site that I use for "title case" any block of text: http://dpoisn.com/tools.php. Just view the source on that. It's all right there. – durbnpoisn Sep 21 '15 at 17:30
  • So you want to write `"Hello world".replace(/(^| )./g, function(a){return a.toUpperCase()})` but more complicated? Briefly: forget about the `myArray`, iterate each character as you do, and check if it is either the start of the `string (i=0)` or preceeded by whitespace `(myString[i-1]==" ")`. If so, change the character to uppercase. Then append the character to `out`. – Kenney Sep 21 '15 at 17:46

1 Answers1

0
var myString = "Hello world!";
var myStringAux = "";

for (var i=0; i < myString.length; i++){
    if(i==0 || myString[i-1] == " ") {
       switch(myString[i]) {
        case "a":
            myStringAux+="A";
            break;
        case "h":
            myStringAux+="H";
            break;
        case "w":
            myStringAux+="W";
            break;
        default:
            myStringAux+= myString[i];
           break; 
           }


    } else {
       myStringAux+=myString[i];

    }



}
myString = myStringAux;
alert(myString)

Also fiddle for playing: https://jsfiddle.net/22xken1e/

You can also do it converting to ascii to avoid cases, but I don't know if you can use this functions

    var myString = "Hello world!";
var myStringAux = "";

for (var i=0; i < myString.length; i++){ 
    if((i==0 || myString[i-1] == " ") && 97<= myString[i].charCodeAt(0) && myString[i].charCodeAt(0) <= 122 ) {
       myStringAux += String.fromCharCode(myString[i].charCodeAt(0) - 32)

    } else {
       myStringAux+=myString[i];

    }

}
alert(myStringAux)
Víctor
  • 3,029
  • 3
  • 28
  • 43