How to convert comma separated string into an array in javascript

var traingIds = "$triningIdArray"; // $triningIdArray this value getting from server alert(traingIds) // alerts <1,2>var type = typeof(traingIds ) alert(type) // // alerts Stringnow i want to lớn convert this to array so that i can iterate

i tried

var trainindIdArray = traingIds.split(",");$.each(trainindIdArray, function(index, value) alert(index + ": " + value); // alerts 0:<1 , & 1:2>);how to resolve sầu this?




Bạn đang xem: How to convert comma separated string into an array in javascript

*

Assuming, as seems to be the case, $triningIdArray is a server-side placeholder that is replaced with JS array-literal syntax, just thua thảm the quotes. So:

var traingIds = $triningIdArray;not

var traingIds = "$triningIdArray";

*

Since array literal notation is still valid JSON, you can use JSON.parse() to convert that string into an array, & from there, use it"s values.

var chạy thử = "<1,2>";parsedTest = JSON.parse(test); //an array <1,2>//access lượt thích & arrayconsole.log(parsedTest<0>); //1console.log(parsedTest<1>); //2

*

Change

var trainindIdArray = traingIds.split(",");

to

var trainindIdArray = traingIds.replace("<","").replace(">","").split(",");

That will basically remove < and > & then split the string




Xem thêm: Download Zsnes Home Page - Download Zsnes Latest Release

*

check this out :)

var traingIds = "<1,2>"; // $triningIdArray this value getting from hệ thống alert(traingIds); // alerts <1,2>var type = typeof(traingIds);alert(type); // // alerts String//remove sầu square bracketstraingIds = traingIds.replace("<","");traingIds = traingIds.replace(">","");alert(traingIds); // alerts 1,2 var trainindIdArray = traingIds.split(",");​for(i = 0; i

*

Thanks for contributing an answer to Staông chồng Overflow!

Please be sure to lớn answer the question. Provide details and share your research!

But avoid

Asking for help, clarification, or responding lớn other answers.Making statements based on opinion; baông xã them up with references or personal experience.

To learn more, see our tips on writing great answers.


Post Your Answer Disthẻ

By clicking “Post Your Answer”, you agree khổng lồ our terms of service, privacy policy & cookie policy


Not the answer you're looking for? Browse other questions tagged javascript jquery or ask your own question.




Xem thêm: Parents' Ultimate Guide To Steam, Parents' Ultimate Guide To Steam

site design / logo sản phẩm © 2021 Stachồng Exchange Inc; user contributions licensed under cc by-sa. rev2021.5.14.39313


Your privacy

By clicking “Accept all cookies”, you agree Staông chồng Exchange can store cookies on your device và discthua information in accordance with our Cookie Policy.


Chuyên mục: