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!
CodePudding user response:
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/'));
CodePudding user response:
Try using the following regex:
\/.*\bbacon\b
If you get a match, it means you have that word in your url. If you need to match it case-insentitively, then you can use the 'i' modifier.
Regex Explanation:
\/
: a slash.*
: any character\bbacon\b
: your hotword between word boundaries
Check the demo here.
EDIT: If you want to match your bacon "word" specifically after the first occurrence, check anubhava's answer.
CodePudding user response:
Have you tried this?
/\/.*bacon/
CodePudding user response:
I would go with a simple one : const regex = /\/.*(bacon)/
function myRegexFunction(url) {
var regex = /\/.*(bacon)/;
if (regex.test(url)) {
return true;
} else {
return false;
}
}
\/
to match after a/
.*
0 to n character(bacon)
your pattern (parenthesis are optional)
Be aware it will not work if your link is http://baconurl/…