2

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>");
});
3
  • 2
    Why not have the controller give you valid JSON? So you could JSON.parse? Commented Jan 20, 2014 at 19:24
  • @RocketHazmat Yep, thought of that. However, I am passing a number of values (different values) to the view. In my case, it would actually be a lot more work. Of course, I would have shown my Java controller code, but it is out of the question's scope. Commented Jan 20, 2014 at 19:33
  • 1
    I agree with @RocketHazmat this sounds somewhat like an XY problem. Commented Jan 20, 2014 at 19:54

3 Answers 3

3

You can do

var arr = "[AB, NK, LK]".slice(1,-1).split(", ")
Sign up to request clarification or add additional context in comments.

Comments

0

With a regular expression

var vals = "[AB, NK, LK]".match(/[A-Z]{2}/g);

Comments

0

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

Please prefer MDN references such as developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… to w3schools references when they're better w3fools.com

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.