1

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.
1
  • aravinth str[2] should be the word "is" by what you are hoping to achieve Commented Mar 8, 2011 at 16:52

6 Answers 6

7

When 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.
Sign up to request clarification or add additional context in comments.

3 Comments

Except that foo[2] actually equals "is".
also str[2] would actually equal 'l'
you are welcome. don't forget to select a correct answer please.
6
var a = str.split(" ");  // split() returns an array, it does not modify str
a[2];  //  returns "is";
a[3];  //  returns "testing";

Comments

3

.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.

Comments

2

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"

Comments

2

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];

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.