How to create an array from text strings in a string?

0

Can someone help me with some method, function, or whatever, to make a string become an array made up of pieces of the same string example:

var string = "stackoverflow";
var array = [];
console.log(array) // ['stack'], ['over'], ['flow']

and / or

var string = "gameoveragain";
var array = [];
console.log(array) // ['game'], ['over'], ['again']'

Well this is what I want as in the examples, something where I can reuse, and that always finds the 'over' section in the string and from there the string becomes a separate array, in this case it can be an array with 3 items 2, 1 or several, if in case it is always found specifically 'over' within the string.

    
asked by anonymous 27.10.2017 / 18:44

2 answers

3
const split = function (string) {
    string = string.split(/(over)/);
    return string;
};

The .split() method will separate a string into substrings and return a array . The parameter I pass in parentheses is the separation parameter of string , that is, the method will split the string when it is found.

In the case I passed a regex parameter so that I can capture the group and add it to the array return%.

To learn more about regex, I recommend:

link

For those who understand English better than YouTube's regex class:

link

    
27.10.2017 / 18:51
1

A more reusable alternative follows.

var _split= function (text, term) {
  var index = 0;
  var terms = [];
  text.replace(new RegExp(term, "gi"), function (term, i) {
    terms.push(text.substring(index, i));
    terms.push(term);
    index = i + term.length;
  });
  terms.push(text.substring(index));
  return terms;
}

var terms = _split("stackoverflowovergame", "over");
console.log(terms);
    
27.10.2017 / 19:03