Skip to content

How to find all string between two characters using Javascript regex

How to find all string between two characters using Javascript regex

In this post we will use javascript regular expression to find all string between two characters. We will get all words that start with ‘b’ and end with ‘r’ using Javascript expression.


Problem

From below list we need to find all word that start with ‘b’ and end with ‘r’. So we should get ‘br’, ‘bar’, ‘baar’, ‘ber’, ‘bear’.

const str = 'fo br bar baar ber bear foo';

Lets start with simple regular expression where we will use the opening and closing square brackets of regular expression as below:-

str.match(/b[a]r/g); // Output ['bar']

No what we expected but a good start. Now let’s add a ‘+’ which will help capture one and more occurrences of ‘a’. So out new expression will be:-

str.match(/b[a]+r/g); // Output ['bar', 'baar']

Ok but ‘br’ is still missing let see what we can do. We can replace the ‘+’ with ‘*’ as it will get zero and more occurrence compare to ‘+’ which gives one and more.

str.match(/b[a]*r/g); // Output ['br', 'bar', 'baar']

Final Solution to find all string between two characters using Javascript regex

So not let’s focus on ‘ber’ and ”bear” part. We canadd ‘e’ with inside the square brackets so the regular expression will search for ‘e’ as well. So after adding ‘e’ voila we get our desired output.

str.match(/b[ae]*r/g); // Output ['br', 'bar', 'baar', 'ber', 'bear']

Conclusion

Hope you like the short explanation on how we can use a regular expression to get all words that start with ‘b’ and end with ‘r’ using Javascript expression. See you in my next post. Till then enjoy coding 🙂

Further Reading

Javascript regex

Please share