Regular expression: Search for a particular word following the initial appearance of a backslash

I need help with creating a regex pattern to find the word "bacon" after the first "/" in a URL.

Here are some examples:

Expected to 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/'));

Expected to 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/'));

This is what I currently have:

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

Any suggestions would be greatly appreciated!

Answer №1

Here is a regex that can be used for this purpose:

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

Check out the RegEx Demo for more details

RegEx Breakdown:

  • ^: Indicates the start of the text
  • [^\/]+: Matches one or more characters that are not a slash (/)
  • \/: Matches a slash (/)
  • [^\/]*: Matches zero or more characters that are not a slash (/)
  • \bbacon\b: Matches the complete word "bacon"
  • .*: Matches any remaining text on the same line

Code Example:

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

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

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

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

Answer №2

Consider trying out this regular expression pattern:

\/.*\bbacon\b

When this pattern produces a match, it indicates the presence of the specified word in the URL. To perform a case-insensitive match, you can utilize the 'i' modifier.

Here's a breakdown of the regex components:

  • \/: denotes a slash
  • .*: represents any character
  • \bbacon\b: indicates the target word enclosed within word boundaries

Feel free to explore a demonstration of this regex here.


UPDATE: For a more specific match for the term "bacon" after the initial occurrence, please refer to anubhava's solution mentioned in the thread.

Answer №3

Have you given this a shot?

/\/.*bacon/

Answer №4

If I had to choose a straightforward approach, I'd recommend using the following regex pattern: const regex = /\/.*(bacon)/

function checkForBacon(url) {
  var regex = /\/.*(bacon)/;
  if (regex.test(url)) {
      return true;
  } else {
      return false;
  }
}
  • \/ matches after a forward slash /
  • .* matches zero or more characters
  • (bacon) defines the pattern to search for (parentheses are optional)

Keep in mind that this regex may fail if your link is like http://baconurl/…

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verifying internet connectivity and updating content using jQuery and JavaScript

Upon loading the page, the following functionality occurs without triggering a click event: The updated code attempts to determine if the internet connection is active. If the connection is off, the 'link' on the page will be disabled (non-click ...

How can we use JavaScript to close a dropdown menu when the user clicks outside of it?

I am facing an issue with my code. I want to close the dropdown menu when clicking outside of it or on the items within the dropdown. How can I achieve this? I attempted to use addEventListener('click', myFunction) on `document` but it did not w ...

Discovering the size and count of JavaScript objects within a browser's memory

Many suggest using the Chrome Profiler Heap Snapshot to analyze memory usage, but I have found that on an empty page (no JavaScript or CSS, just HTML), it shows a heap size of 8MB and anywhere from 12 to 30 thousand objects depending on its mood. This tool ...

Is there a way to retrieve the current object as a JSON string from inside the object using either jquery or javascript?

Looking for a way to return the current instance as a JSON text so that the values can be sent via an ajax request to a server-side script. Uncertain about where to apply the "this" keyword in a jQuery selector function Actor(){ this.input=function(pnam ...

List of random points generated using Three.js

Novice inquiry: I have generated some random points in JavaScript. How can I individually access each point later on? I remember something about an 'Object' that holds all the points, allowing me to manipulate their positions or selectively retri ...

Creating a personalized webview in Appgyver Steroids: A step-by-step guide

I am planning to design the following layout: The main screen will display a web page There should be a sidebar on the left side The sidebar can be accessed by clicking on a 'hamburger' icon in the app header Currently, my app structure look ...

transferring scoped model information to the controller

When using AngularJS, my view is structured like this: <div class="sli1" ng-init="values=[10,20,30,40,50]" <div class="sli2" ng-init="values2=[10,20,30,40,50]" I am attempting to send the initial data models back to the controller for retrieva ...

Combine assorted fabrics and materials in selected designs

Is it possible to incorporate multiple texture maps into a material such as phong? I am aware that using shadermaterial and passing them as uniforms makes it simple to mix them in the shader, but I prefer to utilize existing specular maps, environment map ...

What's the best way to execute multiple actions within a single gulp task?

Is there a way to execute multiple actions within one gulp task? I have tried using event-stream's merge feature following the example in How to perform multiple gulp commands in one task, but it doesn't work properly when combined with the del p ...

Choosing specific anchors based on their corresponding div ids

Just beginning my journey with JS, looking to tackle an issue (I know, everyone says that!). My task is to create a script that can choose an anchor element and inject an <img>. Nested within a div with the id of _nwa_social_logins, there are multipl ...

Generating hills with PlaneGeometry in Three.js

Currently, I am searching for a straightforward technique to generate non-uniform hills in Three.js. By utilizing particles and positioning them with a sine wave algorithm like the following snippet: x = Math.random() * 1000 y = Math.sin( x / freq ) * ...

Sending an email through Node.js with SendGrid is not a challenge

I've got this Mailer.js file const sendgrid = require('sendgrid'); const helper = sendgrid.mail; const keys = require('../config/keys'); class Mailer extends helper.Mail { constructor({ subject, recipients ...

Is it possible to define a variable within a JavaScript function and then access it outside of the function?

I have a Node.js application where I need to define a variable inside a function and access its value outside the function as well. Can someone provide guidance on how to achieve this in my code? var readline = require('readline'); var rl = read ...

Express js is failing to deliver static assets

Hello, I'm having an issue with Express Js. It seems like a beginner problem - static files are not being served properly. const express = require('express'); express() .set('view engine','ejs') .use(express.stat ...

"When testing with an API client, NextJS 13 successfully returns a response, however, the same response

Having trouble getting a clear answer on something really simple. I've created an API route: // /api/test/route.js export async function GET(request, response) { console.log("requested"); return NextResponse.json({ my: "data" ...

Incorporating React into an already existing webpage and accessing URL parameters within a .js file

Following the official guidelines: To include React in a website, visit https://reactjs.org/docs/add-react-to-a-website.html I have created a file named test.html with the following content: <!DOCTYPE html> <html> <head> < ...

Trouble with locating newly created folder in package.json script on Windows 10

I am facing an issue in my Angular application where I am trying to generate a dist folder with scripts inside it, while keeping index.html in the root folder. I have tried using some flag options to achieve this but seem to be stuck. I attempted to automa ...

AngularJS directive created for validation on blur

I am striving to replicate some of the features found in Angular 1.3.X for the app I am developing, with a particular focus on ensuring compatibility with IE 8. Unfortunately, this constraint means that I cannot utilize version 1.3.X. I have encountered di ...

Utilizing Node.js to Retrieve a POST Request JSON and Modify its Format

Received an incoming Post request in JSON format like this: [{"username":"ali","hair_color":"brown","height":1.2},{"username":"marc","hair_color":"blue","height":1.4},{"username":"zehua","hair_color":"black","height":1.8}] Need to transform it into the f ...

Apple Safari 14.0.3 restricts JavaScript from setting a cookie expiry date beyond one week from the current date

This is my second time reaching out with this question, but after plenty of trial and error experimentation, I have gathered much more information to share. I have been attempting different methods to set a cookie in Safari using JavaScript 'document ...