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.

1
  • 1
    emergency['1']['phone']['2']? ... but what do you mean with dynamic? Explain a little bit more. Commented Jul 18, 2018 at 21:00

3 Answers 3

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}]`))

Sign up to request clarification or add additional context in comments.

2 Comments

Good good approach (: +1
Simple, elegant and efficient, thank you!
2
const originalString = 'emergency.1.phone.2'
const desiredString = originalString
  .split('.')
  .reduce((fullPath, arg) => fullPath + `['${arg}']`)

console.log(desiredString)

// logs: emergency['1']['phone']['2']

Comments

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; }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.