I understand that javascript's split() method should take a string and split it into an array based on the parameter(s) passed in the method.
I have run the following in the console:
var sen = 'I love javascript';
sen.split(' ');
console.log(typeof(sen));
So split(' ') should split the string based on whitespace and return an array with 3 strings.
However the console returns the typeof as "string" rather than "object"
Does anyone know why?
asked Jul 24, 2014 at 23:48
HelloWorld
2,3403 gold badges33 silver badges47 bronze badges
1 Answer 1
Because split doesn't change sen. The returnvalue of
sen.split(' ');
would be an array. Try:
var sen = 'I love javascript';
var arr = sen.split(' ');
console.log(typeof(arr));
Sign up to request clarification or add additional context in comments.
3 Comments
HelloWorld
so the problem was that I needed to store the result of sen.split(' ') in a variable. Got it!
jasonscript
@HelloWorld - it would be more correct to say that the split function doesn't modify the original value
HelloWorld
@jasonscript && jhinzmann - If either of you have time would you mind explaining? I understand the split function is used to split a string into an array. Why does it not modify the original value (or the data type for that matter) unless it is stored in a new variable?
lang-js
split?