简体   繁体   中英

Split the string on a delimiter based on conditions

I have a string similar to below

var str = '1;2;3;{"A",B};4;6;{"C","D"}'

I want to convert the str into array seperated by ";"

var array = [str.split(';')];

It is converted to --> ["1","2","3","{"A",B}","4","6","{"C","D"}"]

But I need a array similar to this --> [1,2,3,{"A",B},4,6,{"C","D"}]

All the numbers should be as numeric and string as strings.I know it can be done using loop, but is there an easy way of doing it, because the string in reality is very big with almost 500-600 values.

Check if the input is a number and convert it and to remove the other stuff convert it back to string

var str = '1;2;3;{"A",B};4;6;{"C","D"}'
str.split(';').map(x => {
        if (!isNaN(x)) {
            return parseInt(x, 10)
        }
        return x;
    }).join(',')
    .replace("\"{", "{")
    .replace("\"}", "}")

example string: 1,2,3,{"A",B},4,6,{"C","D}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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