0

I have a string like object/array nodes. need to convert string to nodes, using regular expression

const variableName = "parent1[0].child[2].grandChild['name'].deep_child"; // should be n number of child`

// expected result:
const array = ['parent1',0,'child',2,'grandChild','name','deepChild'];
// Note: array's strings property should be any valid variable name like 'parenet' or 'parent1' or 'PARENT' or '_parent_' or 'deep_child'

Note

3 Answers 3

4

You can get the desired result by using split

[^\w]

enter image description here

after splitting you may get empty strings so you can use a filter to filter out them. At last convert the required number that are in string to type number

const variableName = "parent1[0].child[2].grandChild['name'].deep_child";

const result = variableName
  .split(/[^\w]/)
  .filter(_ => _)
  .map(a => (isNaN(parseInt(a)) ? a : parseInt(a)));
  
console.log(result);

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

Comments

1

Try with regex /[\[\].']+/g.

Regex Evaluator.

enter image description here

This regex catches the group between [ and ]. and splits the string there. Also if ant node of the generated array is a number, convert that to a number using a map function.

const variableName = "parent1[0].child[2].grandChild['name'].deep_child";
const output = variableName
            .split(/[\[\].']+/g)
            .map((node) => isNaN(node) ? node : Number(node));
console.log(output);

5 Comments

It is not completely correct OP wants 0 or 2 as a number not string
Take +1 to 10k. Congo. It feels phenomenal when we see 10k. Right
Regex visualizer make it better to understand.
@decpk how did you generated that image?
@decpk Thats awesome
0

What you are looking for is a split of multiple conditions. A simple and good aproach is to replace all of them except one and finally make the split:

// should be n number of child`
const variableName = "parent1[0].child[2].grandChild['name'].deep_child";

const array = variableName
  .replaceAll("'", "")
  .replaceAll("].", "[")
  .split("[")
  .map((x) => (isNaN(x) ? x : +x));

console.log(array);

2 Comments

It is not completely correct OP wants 0 or 2 as a number not string
It would be easy for everyone to understand it better if you make your code runnable. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.