0

I have a string which is something like this:

apples1h7s5e47epearshrrdjhrdjdrjapples15r4h775h47pearshrmbaewv4kg0kapples15hrs477sr547pears

and I want to get from the string all of the words which are apples to pears and put them in an array. So the output would be:

apples1h7s5e47epears, apples15r4h775h47pears, apples15hrs477sr547pears

Mohsen Alyafei
  • 4,765
  • 3
  • 30
  • 42
Quinten
  • 13
  • 3
  • Sorry, duplicate-closers, do you ever read the question and the content of the 'marked duplicate' when you press the button? This is nonsense!! He didn't ask 'how to find something with regexp'! Pay more attention, please. – Andreas Dolk May 25 '20 at 13:32

3 Answers3

1

Here i split it up, and filter it.

Keep in mind this wont work in IE, you will need an Polyfill

let bigString = "apples1h7s5e47epears hrrdjhrdjdrj apples15r4h775h47pears hrmbaewv4kg0k apples15hrs477sr547pears";

let result = bigString.split(" ").filter(el => el.startsWith("apples") && el.endsWith("pears"))

console.log(result);

startsWith Polyfill:

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}

endsWith Polyfill:

if (!String.prototype.endsWith) {
  String.prototype.endsWith = function(searchString, position) {
      var subjectString = this.toString();
      if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
        position = subjectString.length;
      }
      position -= searchString.length;
      var lastIndex = subjectString.indexOf(searchString, position);
      return lastIndex !== -1 && lastIndex === position;
  };
}
bill.gates
  • 14,145
  • 3
  • 19
  • 47
0

I would suggest parsing the string as a character array first then look for the combination of words and add them to another array you defined. Thats perhaps the most straight forward way to go about but there maybe easier ways out there I mainly work with C# so I am not sure.

0

You can use regex for this

const string = "apples1h7s5e47epears hrrdjhrdjdrj apples15r4h775h47pears hrmbaewv4kg0k apples15hrs477sr547pears"

const data = string.match(/(apples\w*)/g)
console.log(data)

I hope this might help

aatish
  • 57
  • 3