You could do this by using the string .replace
method with a regex with a special replacement function.
The regex is /\.(.+?)(?=\.|$)/g
, which looks for:
- a literal
.
, followed by
- anything, until:
- another literal
.
or the end of the string
Then, you can specify a function which takes the captured string and puts it in brackets, and use that as the replacer.
Example:
const dots = "emergency.1.phone.2"
// Should convert to:
// emergency[1][phone][2]
console.log(dots.replace(/\.(.+?)(?=\.|$)/g, (m, s) => `[${s}]`))