简体   繁体   English

如何将数组字符串解析为数组

[英]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]" .这是一个示例输入"[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.我尝试使用JSON.parse ,如果没有特殊字符,例如"[1,2,3,4]"但使用#这样的特殊字符,我想保持字符在数组中的原样。 So "[1,2,3,#,5]" should be parsed as [1,2,3,#,5] but throws exception instead.所以"[1,2,3,#,5]"应该被解析为[1,2,3,#,5]但会抛出异常。 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. JSON.parse提供了一个 reviver 回调 function 用于特殊处理,但对于这个目的似乎有点过分了,我猜它会有点复杂。 Any help is highly appreciated非常感谢任何帮助

Edit: Reviver callback would not help as it is for transforming parsed object, not for helping parse the object.编辑:Reviver 回调无济于事,因为它用于转换解析的 object,而不是帮助解析 object。 So, that is also ruled out as possible solution因此,这也被排除为可能的解决方案

You can use split and map :您可以使用splitmap

 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]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM