Johnny
Johnny

Reputation: 107

Javascript Split difference

Javascript

var sitename="Welcome to JavaScript Kit"
var words=sitename.split(" ") //split using blank space as delimiter
for (var i=0; i<words.length; i++)
alert(words[i]) 
//4 alerts: "Welcome", "to", "JavaScript", and "Kit"

And

var sitename="Welcome to JavaScript Kit"
var words=sitename.split("") //split using blank space as delimiter
for (var i=0; i<words.length; i++)
alert(words[i]) 
//6 alerts: "W", "e", "l", "c","o","m"

What is the difference between

var words=sitename.split(" ");

And

var words=sitename.split("");

Here, what is the difference between two splits.

Upvotes: 0

Views: 264

Answers (5)

Krish R
Krish R

Reputation: 22711

var words=sitename.split(" ");

This one split the words using the space Welcometo

var words=sitename.split("");

This one split the words using the character. i.e. Separate each charater, including white-space

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

Upvotes: 0

maček
maček

Reputation: 77778

I'm guessing your browser is preventing the alerts from spamming

Don't use alert inspect the .slice result. Use something like console.log to get a better look

console.log("Welcome to JavaScript Kit".split(""));
// ["W", "e", "l", "c", "o", "m", "e", " ", "t", "o", " ", "J", "a", "v", "a", "S", "c", "r", "i", "p", "t", " ", "K", "i", "t"]

And

console.log("Welcome to JavaScript Kit".split(" "));
// ["Welcome", "to", "JavaScript", "Kit"]

Upvotes: 0

gaurav5430
gaurav5430

Reputation: 13882

var words=sitename.split(" ");

this will split around space character

var words=sitename.split("");

this will split around each character

I ran the script and in my browser it is working fine, i get all alerts till the end 't'. may be your browser is not allowing the webpage to generate any more dialogs

Upvotes: 0

Dinesh Dinaz
Dinesh Dinaz

Reputation: 313

    var words=sitename.split(" ");

This code is split by the blank space

    var words=sitename.split("");

But here you didnt given anything so it will be split the char's

Upvotes: 1

var sitename="Welcome to JavaScript Kit"
var words=sitename.split("") //split using blank space as delimiter
for (var i=0; i<words.length; i++)
alert(words[i]) 
//6 alerts: "W", "e", "l", "c","o","m"

It wont stop on just m it will have many more alerts after that.

every word will be alerted till "K" "I" "T" http://jsfiddle.net/zwJJN/

var words=sitename.split("") //split using blank space as delimiter    

var words=sitename.split(" ") //split using white space space as delimiter

When we use split the whole string is searched for the delimiter given and is splitted on the basis of that

var words=sitename.split("")// every character is splitted.

var words=sitename.split(" ")// every words is splitted having white space before it.

Upvotes: 1

Related Questions