开发者

How to convert Char into Strings in JavaScript?

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 test开发者_运维知识库ing.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜