This is what I’ve tried
// input
let input = "{id: 1, name: apple, qty: 2, colors: [{id: 1, hex: #f95}], store: {id: 1, name: Apple Store}}"
let result = input.replace((/([w]+)(:)/g), ""$1"$2");
// {"id": 1, "name": apple, "qty": 2, "colors": [{"id": 1, "hex": #f95}], "store": {"id": 1, "name": Apple Store}}
And then I just replace it like, replaceAll(': ', ': "')
. I think it’s not good practice to resolve it, may there is someone who can help me with this problem, thank you so much.
2
Answers
Thanks for all answers, I tried this way and its works
You can convert the stated string that looks almost like an object into an actual JavaScript object with the following assumptions:
.
[
(array) or{
(object),
or}
Output:
Explanation of regex1:
([,{] *)
— capture group 1:,
or{
, followed by optional spaces(w+)
— capture group 2: 1+ word chars (alphanumeric and underscore):
— literal:
'$1"$2":'
— capture group 1, followed by capture group 2 enclosed in quotes, followed by colonExplanation of regex2:
([,{] *"w+":)
— capture group 1:,
or{
, followed by optional spaces, quote, 1+ word chars, quote, colon(?! *-?[0-9.]+[,}])
— negative lookahead for optional spaces, a number, followed by,
or}
(?! *[{[])
— negative lookahead for optional spaces, followed by{
or[
( *)
— capture group 2: optional spaces([^,}]*)
— capture group 3: everything that is not a,
or}
'$1$2"$3"'
— capture group 1, followed by capture group 2, followed by capture group 3 enclosed in quotesLearn more about regex: https://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex