Javascript: A word with Spaces

Given a word “HELLO”, print the word with spaces “H E L L O”.

Naive Solution:

function spacing(a){
   var b = a.split(''), c = b[0];
   for(var i=1; i < b.length; i++){
       c += " " + b[i];
   }
   console.log(c);
}

spacing('hello');

The output is:

h e l l o

Using Javascript prototypes:

function SetString(stringName){
   this.stringName = stringName;
}

function SpacingFunction(){
   var b = this.stringName.split(''), c = b[0];
   for(var i=1; i < b.length; i++){
      c += " " + b[i];
    }
   console.log(c);
}

SetString.prototype.spacingFunction = SpacingFunction;

new SetString('hello').spacingFunction();

The output is:

h e l l o


Resources:

http://javascriptissexy.com/javascript-prototype-in-plain-detailed-language/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s