Sahil
Sahil

Reputation: 21

array convert string to array angularjs

$scope.stringArray = new Array();
  angular.forEach($scope.questions, function(value, key){
      if(value.type == 'select') {
          var string = value.value;
          console.log(string) //"This is item";
          for(var i =0; i < string.length; i++){
              $scope.stringArray.push(string[i]);
              if(i != string.length-1){
                  $scope.stringArray.push(" ");
              }
          }

      }
  });

it should return

stringArray [0] = "This"; stringArray [1] = "is"; stringArray [2] = "item";

Currently response is like that

stringArray [0] = "T"; stringArray [1] = ""; stringArray [4] = "h"; stringArray [5] = ""; stringArray [6] = "i";...  Please guide

Upvotes: 2

Views: 11352

Answers (2)

Suren Srapyan
Suren Srapyan

Reputation: 68685

You need to split your string by ' ' and add them into the array

var string = value.value.split(' '); // <- split
for(var i = 0; i < string.length; i++){
    $scope.stringArray.push(string[i]);
    if(i != string.length-1) {
       $scope.stringArray.push(" ");
    }
}

Upvotes: 0

void
void

Reputation: 36703

Use String.prototype.split().

$scope.stringArray = string.split(" ");

The issue with your code is that, when you loop through a string index 0 will give you the first character, index 1 will give you the second character. It tokenizes the string based on characters and not on words.

.split(" ") will tokenize the string by spaces and will return an array.

Upvotes: 1

Related Questions