Pratiksha Chaudhary
Pratiksha Chaudhary

Reputation: 21

how to parse an array string into array

I need to convert a string into an array. The only catch is my string could have special character like # in it. Here is a sample input "[1,2,3,#,5]". I tried using JSON.parse which works if there are no special characters, for eg, "[1,2,3,4]" but with special character like #, I want to keep the character as it is in the array. So "[1,2,3,#,5]" should be parsed as [1,2,3,#,5] but throws exception instead. JSON.parse provided a reviver callback function for special handling but seems to be an overkill for the purpose and I am guessing it would be a bit complicated. Any help is highly appreciated

Edit: Reviver callback would not help as it is for transforming parsed object, not for helping parse the object. So, that is also ruled out as possible solution

Upvotes: 1

Views: 126

Answers (2)

Amit11794
Amit11794

Reputation: 158

Here it is trying to convert it into number array, so any other character will throw an error including alphabets and special characters.

Try using this instead -

var output = "[1,2,3,#,5]".replace(/[\[\]']+/g,'').split(",");
console.log(output);  //["1", "2", "3", "#", "5"]

Upvotes: 0

blex
blex

Reputation: 25648

You can use split and map:

const str = "[1,2,3,#,5]";

const arr = str.replace(/(^\[|\]$)/g, '')    // Remove the [] brackets
               .split(',')                   // Split on commas
               .map(x => isNaN(x) ? x : +x); // Convert numbers
               
console.log(arr); // [1, 2, 3, "#", 5]

Upvotes: 2

Related Questions