2

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.

6
  • 1
    Please remember that java has no relationship to javascript. The regex would be different in java, which wouldn't help you. Commented Jun 1, 2021 at 16:35
  • the g modifier is what you're looking for. Commented Jun 1, 2021 at 16:44
  • @Gabriel No, this is not exactly what the OP's looking for. Commented Jun 1, 2021 at 16:44
  • Then he should post his code so we don't have to guess. And to show what he tried so far. Yeah maybe the spaces around Apple were not mistakes. Commented Jun 1, 2021 at 16:46
  • @Gabriel He wants to be sure that the word is surrounded by spaces. The g modifier doesn't ensure this. Commented Jun 1, 2021 at 16:47

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

I cannot use lookbehind as it won't work in IE and safari as far as I know. Also, I need , . ! ? to be included. word boundary will ignore those.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.