Reputation: 21
$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
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
Reputation: 36703
$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