Chip Chip - 3 years ago 173
HTML Question

How to convert a List returned from JSP to an Array of Strings in JavaScript

I'm having a HTML page with JSP in it and returned a List from JSP.

<input type="hidden" id="role" value="${sessionScope.rolePermissionsList}" />


Using JavaScript, i tried to display the List:

var rolesList = document.getElementById('role');
console.log(role.value);


It displayed the below result on the browser's console:

[ PR_1 , PR_2, PR_3, PR_4 ]


I want this output to be converted to an Array of Strings.


I expected the output to be in this way [ "PR_1" , "PR_2", "PR_3",
"PR_4" ]


Can anyone tell me how to achieve that?

Answer Source

Assuming [ PR_1 , PR_2, PR_3, PR_4 ] is a string, you can use the below to convert into an array of strings.

var rolesList = "[PR_1, PR_2, PR_3, PR_4]";
console.log(rolesList.match(/\[(.*?)\]/)[1].split(", "));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download