var str = "This is text 1"; var ani = str.split(" "); console.log(ani);
The above code gives the whole word "this" , whereas for the below code
var str = "This is text 1"; str.split(" "); console.log(str);
It gives result as the first character of the string.
Why didn't the later code result was same to the first one?
str.split(" ")to a variable works, but the value of str is not changed.
str.split(" ")does not modify the
strvariable, it returns a new array containing the result.
strstill contains the original string, and
stris the first character of that string.
If you want to do it without assigning to a variable, apply the subscript to the function call:
.split()doesn't mutate / affect the variable it is called on, it instead returns a new value - which you have assigned to
ani. The confusing thing for the example you have is that strings can be accessed like arrays. So
str[index]will give the character at that position.