I've inherited a database that stores an array of strings in the following format:
{"First","Second","Third","Fourth"}
This is output as an ordered list in the application. We're replacing the front-end mobile app at the moment (ionic / angular) and want to do an ngFor over this array. In the first iteration, we did a quick and dirty replace on the curly brackets and then split the string on "," but would like to use a better method.
What is the best method for treating this type of string as an array?
You could do a string replacement of braces to brackets:
str.replace(/{(.*)}/, '[$1]')
This particular string could then be parsed as an array (via JSON.parse).
If you're looking to do the parsing to an array on the front end, would this work?:
const oldStyle = '{"First","Second","Third","Fourth"}' const parseOldStyleToArray = input => input .replace(/[\\{\\}]/g, '') .split(',') .map(item => item.replace(/\\"/g, '')) const result = parseOldStyleToArray(oldStyle) console.dir(result)
Another way to do more widest replacement by key:value
mapping.
str = '{"First","Second","Third","Fourth"}'; mapping = { '{': '[', '}': ']' } result = str.replace(/[{}]/g, m => mapping[m]); console.log(result);
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.