I’m wanting to use regex to look for the word "bacon" after the first "/" occurrence.
For example:
Should return true:
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 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 wordbacon.*: 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/'));