Akash Kumar
Akash Kumar

Reputation: 21

Regex for multiple word match seperated by spaces

I want to match all occurences of a word in a string having spaces at front and back.

Eg: String: " Apple Apple Apple Apple ".

Here I want the match to be " Apple " and there should be 4 matches for the above scenario.

If I just put regex as / Apple /, then only 1st and 3rd are matched.

I know that we can do this with lookahead and lookbehind in regex but it is not supported in safari and IE.

Upvotes: 2

Views: 91

Answers (2)

logi-kal
logi-kal

Reputation: 7880

If you're happy to just match the Apple word, you can use (?<= )Apple(?= ).

If the space is not strictly necessary (e.g. you want also to catch the first word of the string, which is not preceded by a space), you must use word boundaries (i.e. \bApple\b).

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163217

You can match Apple and assert a space to the right. As you know that the space is there, you can add it in the result.

const regex = / Apple(?= )/g;
const s = " Apple Apple Apple Apple ";
console.log(Array.from(s.matchAll(regex), m => m[0] + " "));

Or you can capture Apple in group 1, and get the group 1 value denoted by m[1] in the code:

const regex = /(?=( Apple ))/g;
const s = " Apple Apple Apple Apple ";
console.log(Array.from(s.matchAll(regex), m => m[1]));

Upvotes: 2

Related Questions