Divide person [0] .email into ['person', '0', 'email']

I do not know if this was asked before because English is not my first language, and I do not know the keywords to search.

So basically I have the following input element,

<input type="email" name="person[0].email" /> 

I would like to split the name into 3 parts, for example ["person", "0", "email"] .

I tried using /(\[[^[\]]])|\./ ( /(\[[^[\]]])|\./ , but it gives ["person", "[0]", "", undefined, "email"] . In addition, for a[0][1].b[3].c it should output ["a", "0", "1", "b", "3", "c"]

+5
source share
4 answers

You can use .match instead of .split

 console.log("person[0].email".match(/\w+/g)); 

Note (thanks @npinti ): in case there is _ in the name, my first example will also match _ , so in this case you just need to use regexp, like this

  console.log("person[0].email".match(/[A-Za-z0-9]+/g)); 
+5
source

It looks like you want to break everything that is not a letter or a number, so you can use this: [^A-Za-z0-9]+ . An example expression is available here .

+1
source

You can use this split:

 var m = person[0].email".split(/[.\[\]]+/g) //=> ["person", "0", "email"] 

OR

 m = "a[0][1].b[3].c".split(/[.\[\]]+/g) //=> ["a", "0", "1", "b", "3", "c"] 
0
source

If you always have the following format: name[i].prop , you can do this without regular expressions:

 function splitName(s) { var parts1 = s.split('].'); var parts2 = parts1[0].split('['); return [parts2[0], parts2[1], parts1[1]]; } document.body.innerHTML += JSON.stringify(splitName('name[i].prop')) + '<br/>'; document.body.innerHTML += JSON.stringify(splitName('person[0].email')) + '<br/>'; document.body.innerHTML += JSON.stringify(splitName('a[0].b')) + '<br/>'; 

It is less elegant, not universal and works only for the specified format. However, there are no regular expressions, and if you work only with this format, then why not? :)

0
source

Source: https://habr.com/ru/post/1237547/


All Articles