JavaScript sequential split () for dot notation variables

I have this variable:

var myVar = "r.object.subobject.variable";

I want to add each of the "levels" of this string to an array. My array will contain:

"r.object"
"r.object.subobject"
"r.object.subobject.variable"

I know that I can use the split () JavaScript function with RegEx, but the one I have returns a whole string. For example, I try:

var myArray = myVar.split(/r[.].+/);

Thus, it myArray[0]always appears as "r.object.subobject.variable".

How can I do myArray[0] = "r.object", myArray[1] = "r.object.subobject"and myArray[2] = "r.object.subobject.variable"?

I hope I just don’t understand how regular expressions work, instead of doing some far-fetched recursion or concatenation of the array, dividing only into periods.

Additional restrictions and reference information

  • 1 , , . r. ( while, , .)
  • , .
  • , - , . ( , , AS3, .)
+4
3

, myArray[0] . /r[.].+/ , ( ). .+, char, :

r.object.subobject.variable
--^                       ^      [1]: matched by r[.]
1 |           2           |
  +------------------------      [2]: matched my .+

( "." ), :

var myArray = myVar.split(/[.]/);

EDIT. , .

, , :

var myVar = "r.object.subobject.variable";
var mySplit = myVar.split(".");
var myArray = Array();

for (i = 2; i <= mySplit.length; i++) { 
    myArray.push(mySplit.slice(0,i).join("."));
}


document.write(myArray);
Hide result
+2

.split() RegExp /\./, do.. while, Array.prototype.slice(), Array.prototype.join(), Array.prototype.splice()

var myVar = "r.object.subobject.variable";
var arr = myVar.split(/\./),
  len = arr.length,
  i = 0,
  myArray = [];
do {
  myArray.push(arr.slice(0, i).join("."));
  ++i;
} while (myArray.length <= len);
myArray.splice(0, 2);
console.log(myArray);
Hide result
+1

, , , javasacript (? R), . , .

function levels(str) {
  var levels;
  return str.split('.').reduce(function(acc, level, index) {
    if(index > 0) {
       levels = levels + '.' + level
       acc.push(levels);
    } else {
      levels = level;
    }
    return acc;
  }, []);
}

document.getElementById('results').innerHTML = JSON.stringify(levels('r.object.subobject.variable'), null, '\t');
<pre id="results"></pre>
Hide result
0
source

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


All Articles