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

Having trouble with jQuery functionality when using Laravel 7 mix

Hey there! I'm currently using Laravel Mix to compile all my JS files, but I'm running into an issue with jQuery not working. I've tried adding the defer attribute, but no luck. Can anyone help me troubleshoot this? Thanks! Here's a sn ...

Using a function with a parameter as an argument in an event handler

Imagine you have the code snippet below: $('#from').focus(listExpand(1)); $('#to').focus(listExpand(3)); I am facing an issue as the code is not behaving as expected. I believe the problem lies in passing a function result instead of ...

Transform Text into Numeric Value/Date or Null if Text is Invalid

Consider the TypeScript interface below: export interface Model { numberValue: number; dateValue: Date; } I have initialized instances of this interface by setting the properties to empty strings: let model1: Model = { numberValue: +'', ...

Is WordPress ajax showing a 404 error for bad requests?

Here is the error message that I encountered POST http://localhost/...../wp-admin/admin-ajax.php 400 (Bad Request) send @ load-scripts.php?c=1…e,utils&ver=4.9.8:4 ajax @ load-scripts.php?c=1…e,utils&ver=4.9.8:4 (anonymous) @ my-ajax-handler ...

"Enhance your web development with TypeScript and react-select

I find myself in a peculiar predicament. Currently, I am immersing myself in learning TypeScript and here is a brief overview of what transpired so far: const [selectedBankCode , setSelectedBankCode] = useState<string | undefined>(); const [selecte ...

Angular's text interpolation fails to update when a value is changed by an eventListener

I am encountering an issue with two angular apps, one acting as the parent and the other as the child within an iframe. The HTML structure is quite simple: <div class="first"> <label>{{postedMessage}}</label> </div> &l ...

What is the best way to conduct a conditional check across all subsequent visible rows of a table?

When a user clicks inside the text input field and presses either the down or up arrow keys, my JavaScript function is triggered. The purpose of this functionality is to search table values and allow the user to select one by pressing the arrow keys. Every ...

Best Practices for Implementing Redux Prop Types in Typescript React Components to Eliminate TypeScript Warnings

Suppose you have a React component: interface Chat { someId: string; } export const Chat = (props: Chat) => {} and someId is defined in your mapStateToProps: function mapStateToProps(state: State) { return { someId: state.someId || '' ...

Include a conditional statement in ng keypress

When a user types a specific value into a text input, I want to display a specific div. This is what my template looks like: <input type="text" id="jobTitle" (click)="autoCompleteClick()" (keypress)="autoCompleteKeypress()" name="autocomplete" place ...

Error encountered in Typescript when handling fetch options as a variable

Why does this code compile perfectly? fetch('someurl', { method: 'GET', credentials:"same-origin" }) However, the following code throws a compilation error for fetch('someurl', init); const init = { method: &apo ...

Locating strings within Text Files utilizing Python

Currently, I am in need of a software that can identify how many times a specific string (S) appears in a particular file (P). To achieve this, I have crafted the following function: def find_string_in_file(P, S): file1 = open(P, 'r') patter ...

Is there a way for me to move the dot icon along the dotline?

Here is the code snippet: jsFiddle I have successfully implemented a click event to change the style of selected dots in dotline. Now, my query is : How can I enable dragging functionality for the dot icon within dotline? Your assistance on this matte ...

Is Typescript the Ultimate Replacement for propTypes in React Development?

After diving into Typescript for the first time and exploring related articles, it appears that when using Typescript with React, propTypes definitions may no longer be necessary. However, upon examining some of the most popular React Component Libraries: ...

Ascending to the Peak within a div

<script type="text/javascript"> $(document).ready(function(){ updateContent(); }); function updateContent(){ $('#mainDiv').load('home.php', function(){ scrollToTop(); }); } ...

After making an Ajax call using AngularJS in a PHP file, I expected to receive only a success or fail message. Instead, I received the entire HTML page code along

After making an Ajax call using AngularJS in a PHP file, I expected to receive only a success/fail message. However, I ended up receiving the full HTML page code along with tags. Here is my AngularJS code: $http.post('ajax_Location.php',{ &apos ...

Interactive navigation and delayed loading

After generating a set of 80 images in PHP using a for loop, I realized that the loading time is too slow. To address this issue, I attempted to incorporate lazy loading into my gallery by utilizing jQuery's simplePager and lazyLoad plugins. Despite m ...

What is the best way to enhance the capabilities of a current tinyMCE button?

I am interested in enhancing the capabilities of the default buttons in tinyMCE by adding additional functionality. I'm curious to know how this can be achieved. For instance, If I would like the paste button not only to paste content, but also perf ...

Tips for adding and deleting elements after cloning in jQuery

I'm trying to achieve a layout similar to the one shown in this picture. It should display a delete button for each item and an add button to add more items. Check out the example here. I have managed to display the buttons individually, but I'm ...

You cannot employ typed arguments in combination with Typescript within the VueJS framework

I'm struggling to develop a typescript vue component with some methods. Here is the script snippet. <script lang="ts"> import Vue from 'vue'; export default Vue.extend({ methods: { check(value: number) { console.log(valu ...

Trying to determine the specific key of an object based on its value in TypeScript?

Looking to create a function that can retrieve the key for a given value. type Items<T> = Exclude<{ [P in keyof T]: [P, T[P]]; }[keyof T], undefined>[]; export const getKeyName = <T extends Record<PropertyKey, unknown>, V>( col ...