1

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

2

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]

Sign up to request clarification or add additional context in comments.

Comments

0

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"]

Comments

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.