问题
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?
回答1:
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).
回答2:
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)
回答3:
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);
来源:https://stackoverflow.com/questions/51711050/converting-an-array-in-curly-braces-to-a-square-bracketed-array