How to Create an array from text snippets of a string?

Asked

Viewed 681 times

0

Could someone help me, with some method, function or what is available, to make a string become an array made of pieces of the same example string:

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 that’s what I want as in the examples, something where I can reuse, and that always finds the 'over' chunk 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 the case it is always found specifically 'over' inside the string.

2 answers

3


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

The method .split() will separate a string in substrings and return a array. The parameter I pass between parentheses is the separation parameter of string, that is, the method will divide the string where he is found.

In case I passed a regex parameter to be able to capture the group and add it to the array return.

To learn more about regex, I recommend:

http://aprenda.vidageek.net/aprenda/regex

For those who understand English better Youtube regex class:

https://www.youtube.com/playlist?list=PLRqwX-V7Uu6YEypLuls7iidwHMdCM6o2w

  • Good +1! Can you explain how the split works in this case with eregx? So the answer becomes more complete.

  • Thank you very much for the response and recommendations of study links, I really need to learn a lot of this, the algorithm is very simple, I just did not understand how the split works with regex, before asking the question here, I tried to do something using split, but no!

1

Follows a more reusable alternative.

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);

  • thank you very much for the reply!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.