Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

strange [] -> . conversion #1

Closed
rodneyrehm opened this issue May 25, 2016 · 3 comments
Closed

strange [] -> . conversion #1

rodneyrehm opened this issue May 25, 2016 · 3 comments

Comments

@rodneyrehm
Copy link

Hey there,

is there a particular reason for using nested .replace() calls instead of using the capture group directly?

const text = 'due.b[0][0][0]';

const original = text.replace(/(\[.*\])/g, (str) => {
  return str
    .replace(/\[/g, '.')
    .replace(/\]/g, '');
});

const optimized = text.replace(/\[([^\]]+)\]/g, (match, token) => '.' + token);

console.log(text);
console.log(original);
console.log(optimized);
@zewish
Copy link
Owner

zewish commented May 27, 2016

You could try to run the unit tests - one of the cases breaks here. I'm quite sure with some work it could be optimized though.

@rodneyrehm
Copy link
Author

I see. This is happenning because you seem to allow nesting [due][a[0]]. In that case you can still remove the outer replacement and go with

path
  .replace(/\[/g, '.')
  .replace(/\]/g, '')
  .replace(/^\./, '')
  .split('.')

Anyway, my question "if there was a reason to…" is answered :)

@zewish
Copy link
Owner

zewish commented May 27, 2016

Thanks, for that one - will do a new build with a mention to you github alias :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants