I'm using the split(' ')
method in JavaScript to spilt the word for whitespaces.
For example:
I have text like:
var str ="Hello this is testing"
After I call
str.split(' ')
Now I will get Hello this is tesing as output and when I do this
str[2]
I get "l", but I want to get "testing" word (as per array index). How to convert str to array, so that if I put
str[2] //It should be testing.
I'm using the split(' ')
method in JavaScript to spilt the word for whitespaces.
For example:
I have text like:
var str ="Hello this is testing"
After I call
str.split(' ')
Now I will get Hello this is tesing as output and when I do this
str[2]
I get "l", but I want to get "testing" word (as per array index). How to convert str to array, so that if I put
str[2] //It should be testing.
Share
Improve this question
edited Mar 28, 2011 at 18:06
Peter Mortensen
31.6k22 gold badges110 silver badges133 bronze badges
asked Mar 8, 2011 at 16:48
Ant'sAnt's
13.8k28 gold badges102 silver badges148 bronze badges
1
- aravinth str[2] should be the word "is" by what you are hoping to achieve – Matthew Cox Commented Mar 8, 2011 at 16:52
6 Answers
Reset to default 7When you do split it actually returns a value.
var foo = str.split(' ');
foo[2] == 'is' // true
foo[3] == 'testing' // true
str[2] == 'l' // because this is the old str which never got changed.
var a = str.split(" "); // split() returns an array, it does not modify str
a[2]; // returns "is";
a[3]; // returns "testing";
.split()
is returning your array, it doesn't change the value of your existing variable
example...
var str = "Hello this is testing";
var str_array = str.split(' ');
document.write(str_array[3]); //will give you your expected result.
Strings are not mutable, split
[docs] returns an array. You have to assign the return value to a variable. E.g.:
> var str ="Hello this is testing";
undefined
> str = str.split(' ');
["Hello", "this", "is", "testing"]
> str[3]
"testing"
Writing str.split(" ")
does not modify str
.
Rather, it returns a new array containing the words.
You can write
var words = str.split(" ");
var aWord = words[1];
I made this html page and it reports the following:
function getStrs()
{
var str = "Hello this is testing";
var array = str.split(' ');
for(var i=0; i < 4; i ++)
alert(array[i]);
}
It reported Hello ... this ... is ... testing