Regular expressions that identify text located at the conclusion of a URL

Although the title may not be entirely appropriate, my goal is to create a regex that will remove any trailing '/' at the end of a URL under certain conditions.

For example:

http://stackoverflow.com/questions/ask/
to
http://stackoverflow.com/questions/ask

I initially achieved this using ^(.*)\/ (see example), but now I require a modification and I'm uncertain about how it should be done.

The change I need is to NOT remove the '/' if it is on the main page:

http://stackoverflow.com/ stays http://stackoverflow.com/
http://stackoverflow.com/questions/ changes to ttp://stackoverflow.com/questions

In my understanding, the condition should involve checking if the URL ends with text between two '/' characters and does not contain any '.' character. However, I am struggling to implement this condition successfully.

What approach should be taken?

EDIT

Sometimes the URLs may not include 'http' or 'https', so it would be acceptable if the regex worked on ordinary text as well.

Answer №1

When the URL begins with http:// or https://, you can apply the following pattern.

(http[s]*://.*?/.*)/$

Answer №2

If you want to remove the forward slash only when it's at the end of a string, but keep it if it signifies a path on your site, there is a simple way to achieve that.

All you need to do is check whether the forward slash is the last character in the string. The following regular expression accomplishes this task:

(?(?=\/$)(.+)\/)

This regex includes an if statement to verify if the forward slash appears as the final character. If so, it captures everything before the slash.

Answer №3

Here is a useful regular expression pattern:

(.*\.[a-z]+\/?(?:[\w]+(?:\/[\w]+)*)*)

After applying this regex, the result can be found in Group1. For an example of how this works, check out this link: https://regex101.com/r/egAQvX/6

Answer №4

Utilizing this technique can be beneficial:

^(http[s]?:\/\/[^\/]*)(.*)\/

The specified URL will be Group 1 plus Group 2.

If Group 2 is empty:
   1. It represents the main URL
   2. Remember to append a "/" at the end
Otherwise:
   1. It is **not** the main URL
   2. Retain it in its current form

[Check out the Regex Demo]

Answer №5

When expanding on your current approach, you might want to consider utilizing the pattern

/^(?!(?:[^:]+:\/\/)?[^\/]+\/$)(.*)\/$/
. Alternatively, you could opt to exclude whitespace characters with this pattern:
/^(?!(?:[^\s:]+:\/\/)?[^\/\s]+\/$)(.*)\/$/
– Wiktor Stribiżew

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

mongodb is experiencing issues with the findOneAndUpdate operation

Below is the code snippet for updating the database. let profileUrl = 'example' UserSchemaModel.findOneAndUpdate({_id:userId}, {$set: {profileUrl:profileUrl} }, {new:true}) .then((updatedUser:UserModel) => { console.log(updatedUser.profil ...

Utilize Regex to isolate text between specified string markers

I am attempting to scrape a website and I need to extract the JSON data from the data variable in the JavaScript code below using Python Regex. <script type="text/javascript"> P.when('A').register("ImageBlockATF", function(A){ var data ...

Obtain the alternative attribute value from the adjacent element and save it to a variable using jQuery

I'm a beginner with jquery and am trying my hand at creating a simple drag and drop game using the following HTML structure: <div class="set-text"> <div class="text">cinema</div> <div class="text">post-office</div> ...

Achieving selective exclusion of specific keys/values while iterating through an array and rendering them on a table using Angular

Currently facing a hurdle and seeking advice I am developing an angular application that fetches data from an API and presents it on the page The service I am utilizing is named "Api Service" which uses HTTPClient to make API calls apiservice.service.ts ...

Error encountered using jQuery $.post: TypeError - e.type is not a valid function

I'm currently in the process of developing a feedback script specifically for the ZetaBoards forum software. My approach has been to create a $.post function, but when I attempt to submit the form by clicking the submit button, all I get in return is ...

The issue arises when attempting to invoke a method from a global mixin in a Vue3 TypeScript component

I've been working on this challenge for the past week, and I would appreciate any help or insights from those who may have experience in this area. Currently, I am in the process of converting vue2-based code to vue3 for a new project. Instead of usi ...

The 'catch' property is not found within the type 'PromiseLike<void>'

Help! I'm encountering a Typescript Error. An issue is arising with the 'catch' property on type 'PromiseLike<void>'. I am using Ionic and facing an error in the line containing catch: sendrequest(req: connreq) { var p ...

Sending information through a form via a POST request after clicking on a hyperlink

I am attempting to submit a form using POST by clicking on a link and passing some hidden values. This is the code I'm currently using: $( document ).ready(function() { $('a#campoA').click(function() { $.post('testForm2.php', { ...

Incorporating a custom transpiled file format into Typescript imports

I am trying to import a file format .xyz that does not have fixed types for all instances of the format: import { Comment, Article, User } from "./Blog.xyz" However, I keep getting this error message: TS2307: Cannot find module './Blog.xy ...

What are some strategies for distinguishing between callable and newable types?

I seem to be facing a challenge related to narrowing, specifically the differentiation between Fnc (callable) and Class (newable). The code snippet provided functions in Playground, but the autocomplete feature is lacking, as shown in the first image. My ...

What is the method for utilizing Jquery to target the width value of an inline property?

I am struggling with selecting the "style=:width: 10%" value using jquery for a progress bar element in bootstrap. <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 10% ...

When using jQuery with a large selectbox, you may encounter the error message: "Uncaught RangeError: Maximum

My select box works fine in IE and Mozilla, but throws an uncaught rangeError in Chrome when choosing the "Others" option to display a second select box with over 10k options. How can I diagnose and resolve this issue? <!DOCTYPE html> ...

What are the methods to determine the cause of ESLint's slow performance?

Looking to analyze the performance of ESLint in my application. So far, I have only come across one profiling tool provided by ESLint which is the TIMING=1 environment variable. Combining this with DEBUG=eslint:cli-engine allows me to see timing results pe ...

Looking for a jQuery plugin that helps with form alignment?

In a blog post comment, I came across an interesting jQuery form alignment plugin: jQuery.fn.autoWidth = function(options) { var settings = { limitWidth : false } if(options) { jQuery.extend(settings, options); }; ...

Blending PHP with jQuery

I'm currently working on the same page as before but this time, I'm using it to experiment with jQuery. I'm trying to learn it for my 'boss', but unfortunately, I can't seem to get the JavaScript in this file to run at all, le ...

Is there a way for me to transfer parameters between pages on my website?

Utilizing Jquery along with functions like localStorage.setItem() and localStorage.getItem(), I have been able to transfer parameters from one page to another. However, I am uncertain about how to integrate this functionality into the backend code. For i ...

The utilization of `ngSwitch` in Angular for managing and displaying

I am brand new to Angular and I'm attempting to implement Form Validation within a SwitchCase scenario. In the SwitchCase 0, there is a form that I want to submit while simultaneously transitioning the view to SwitchCase 1. The Form Validation is fun ...

Adjust the size of the sliding tool with images of varying dimensions

My mobile-first slider features three different types of images: tall, horizontally long, and square. I want the size of the slider to be determined by the horizontally long image and then scale and center the other images to fit its size. To achieve this, ...

Disabling specific time slots in the mat select functionality

I have a scenario where I need to display time slots at 30-minute intervals using Mat Select. export const TIME=["12:00 AM","12:30 AM","01:00 AM","01:30 AM","02:00 AM","02:30 AM","03:00 AM&qu ...

Using JavaScript to create customized checkboxes is a useful way to

I am looking to develop a JavaScript code that saves all the checkboxes selected by a user. When the user clicks on the finish button, the code should display what they have chosen (text within the label). Admittedly, I am unsure of how to proceed and wou ...