I have a Spring Controller which passes a Set of Strings to the view but as a single String:
"[AB, NK, LK]"
However, I need to convert the above String into an equivalent JavaScript array like the following:
["AB", "NK", "LK"]
I have tried the following jQuery to iterate through the String "[AB, NK, LK]" in order to add these values to a <select> tag:
$.each(arrayCodes, function(index, value) {
$("#select").append("<option value='" + value + "'>" + arrayCodeValues[index]
+ "</option>");
});
asked Jan 20, 2014 at 19:22
blackpanther
11.5k12 gold badges53 silver badges79 bronze badges
3 Answers 3
You can do
var arr = "[AB, NK, LK]".slice(1,-1).split(", ")
answered Jan 20, 2014 at 19:24
Denys Séguret
384k90 gold badges813 silver badges780 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
With a regular expression
var vals = "[AB, NK, LK]".match(/[A-Z]{2}/g);
answered Jan 20, 2014 at 19:28
epascarello
208k20 gold badges206 silver badges246 bronze badges
Comments
Check the use of split function here if you want http://www.w3schools.com/jsref/jsref_split.asp this could solve your problem.
var sText = "[AB, NK, LK]";
var arrayCodes= str.split(",");
$.each(arrayCodes, function(index, value) {
$("#select").append("<option value='" + value + "'>" + arrayCodeValues[index]
+ "</option>");
});
1 Comment
Benjamin Gruenbaum
Please prefer MDN references such as developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… to w3schools references when they're better w3fools.com
lang-js
JSON.parse?