1

I'm trying to figure out how to replace a string in dot notation with square brackets:

emergency.1.phone.2

Should convert to:

emergency[1][phone][2]

I'm trying to make it dynamic so it will convert the string regardless of how many dots there are.

user1347026
  • 588
  • 1
  • 8
  • 14

3 Answers3

8

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}]`))
CRice
  • 29,968
  • 4
  • 57
  • 70
2
const originalString = 'emergency.1.phone.2'
const desiredString = originalString
  .split('.')
  .reduce((fullPath, arg) => fullPath + `['${arg}']`)

console.log(desiredString)

// logs: emergency['1']['phone']['2']
Ben Steward
  • 2,338
  • 1
  • 13
  • 23
1

An alternative is using the function reduce.

let str = "emergency.1.phone.2",
    arr = str.split('.'),
    result = arr.reduce((a, s, i) => i === 0 ? s : a + `[${s}]`);
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Ele
  • 33,468
  • 7
  • 37
  • 75