Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex: Look for a specific word after the first backslash occurrence

I’m wanting to use regex to look for the word "bacon" after the first "/" occurrence.

For example:

Should return true:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

console.log('1 - ', myRegexFunction('www.bacondelivery.com/weekly-bacon-delivery/'));
console.log('2 - ', myRegexFunction('www.bacondelivery.com/daily-bacon-delivery/'));
console.log('3 - ', myRegexFunction('www.bacondelivery.com/bacon-of-the-month-club/'));

Should return false:

console.log('4 - ', myRegexFunction('www.bacondelivery.com/'));
console.log('5 - ', myRegexFunction('www.bacondelivery.com/?some_param'));
console.log('6 - ', myRegexFunction('www.bacondelivery.com/about/'));
console.log('7 - ', myRegexFunction('www.bacondelivery.com/contact-us/'));

Here’s what I currently have:

function myRegexFunction(url) {
  var regex = new RegExp("^([a-z0-9]{5,})$");
  if (regex.test(url)) {
      return true;
  } else {
      return false;
  }
}

Thanks!

>Solution :

You may use this regex for this:

^[^\/]+\/[^\/]*\bbacon\b.*

RegEx Demo

RegEx Details:

  • ^: Start
  • [^\/]+: Match 1 or more of any character that is not a /
  • \/: Match a /
  • [^\/]*: Match 0 or more of any character that is not a /
  • \bbacon\b: Match complete word bacon
  • .*: Match remaining text on this line

Code:

function myRegexFunction(url) {
  const regex = /^[^\/]+\/[^\/]*\bbacon\b.*/;
  return regex.test(url);
}

console.log('1 - ', myRegexFunction('www.bacondelivery.com/weekly-bacon-delivery/'));

console.log('2 - ', myRegexFunction('www.bacondelivery.com/daily-bacon-delivery/'));
console.log('3 - ', myRegexFunction('www.bacondelivery.com/bacon-of-the-month-club/'));

console.log('4 - ', myRegexFunction('www.bacondelivery.com/'));
console.log('5 - ', myRegexFunction('www.bacondelivery.com/?some_param'));
console.log('6 - ', myRegexFunction('www.bacondelivery.com/about/'));
console.log('7 - ', myRegexFunction('www.bacondelivery.com/contact-us/'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading