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
2 Answers 2
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]
Comments
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"]