I have a single string value like 15,16,17 and i want to convert it as ["15","16","17"] using angular js 1.x or java script.Please help me
My Angular js code is
<!DOCTYPE html>
<html>
<script src=".6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
Array items
<code style="display: block; padding: 8px;">{{selected | json}}</code>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.selected = [];
$scope.selected = ["15","16","17"];
$scope.existvalues=15,16,17;
//$scope.selected=$scope.existvalues;
/*Instead of above static code i want assign a ma separated string dynamic value like
this $scope.existvalues=15,16,17;
How i convert and assign $scope.existvalues to $scope.selected array like ["15","16","17"]
*/
});
</script>
</body>
</html>
I have a single string value like 15,16,17 and i want to convert it as ["15","16","17"] using angular js 1.x or java script.Please help me
My Angular js code is
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis./ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
Array items
<code style="display: block; padding: 8px;">{{selected | json}}</code>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.selected = [];
$scope.selected = ["15","16","17"];
$scope.existvalues=15,16,17;
//$scope.selected=$scope.existvalues;
/*Instead of above static code i want assign a ma separated string dynamic value like
this $scope.existvalues=15,16,17;
How i convert and assign $scope.existvalues to $scope.selected array like ["15","16","17"]
*/
});
</script>
</body>
</html>
Share
Improve this question
asked Jun 6, 2018 at 12:35
Sherin GreenSherin Green
3581 gold badge3 silver badges21 bronze badges
1
- Possible duplicate of Javascript Equivalent to PHP Explode() – Javid Asgarov Commented Jun 6, 2018 at 12:38
2 Answers
Reset to default 5use split()
to convert a string to an array
var str = "15,16,17"
var strArr = str.split(',');
console.log(strArr); // gives ["15","16","17"];
or to put it into terms as per your example
$scope.existvalues="15,16,17";
$scope.selected = $scope.existvalues.split(',');
console.log($scope.selected); // gives ["15","16","17"]
Use Split method for strings, it will split the string based what you have asked it to split ("split by ,
here") and return the answer as an Array
str = "15,16,17"
strAsArray = str.split(",")
console.log(strAsArray)