0

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.com/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 comma 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>

1

2 Answers 2

5

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

Comments

1

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)

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.