Looking to find a way to identify strings with hyphens in JavaScript?

I am trying to extract specific parts of a URL that follow a certain pattern like the one below:

http://example.com/somepath/this-is-composed-of-hypens-3144/someotherpath

Specifically, I am interested in extracting the portion of the URL that consists of hyphens and ends with numbers. In the given example URL, I want to extract this-is-composed-of-hypens-3144. My current approach involves using the regex pattern below:

const re = /[a-z]*-[a-z]*-[0-9]*/gis;
const match = re.exec(url);
return (match && match.length) ? match[0] : null;

However, this approach only works if there are two hyphens in the URL. In reality, the number of hyphens can vary. How can I modify my regex pattern to accommodate URLs with a variable number of hyphens?

Answer №1

Feel free to utilize

/\/([a-z]+(?:-[a-z]+)*-[0-9]+)(?:\/|$)/i

Check out the regex demonstration

Specifics

  • \/ - signifies a / character
  • ([a-z]+(?:-[a-z]*)*-[0-9]+) - Group 1 capturing:
    • [a-z]+ - 1 or more ASCII letters
    • (?:-[a-z]+)* - 0 or more instances of - followed by 1 or more ASCII letters
  • (?:\/|$) - either / or end of the string.

If there can be any word characters, not just ASCII letters, you can substitute each [a-z] with \w.

var s = "http://example.com/somepath/this-is-composed-of-hypens-3144/someotherpath";
var m = s.match(/\/([a-z]+(?:-[a-z]+)*-[0-9]+)(?:\/|$)/i);
if (m) {
  console.log(m[1]);
}

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

Executing a custom object function in AngularJS by using the ng-click directive

As I navigate my way through AngularJS, I find myself grappling with the concept of calling a custom method of an object and wonder if there's a simpler approach: https://jsfiddle.net/f4ew9csr/3/ <div ng-app="myApp" ng-controller="myCtrl as myCtr ...

What is the proper way to implement v-model for a custom component within the Vue render function?

Below is the code that I am working with: ... var label_key_map = { a: "1", b: "2", c: "3", d: "4" } render: (h) => { var form_data = {} for (let key in label_key_map) { var form_item = h( 'FormItem', {props: {prop: key}}, ...

Is it possible to call a JavaScript file located inside a Maven dependency's jar?

In the process of developing a Spring MVC web application using Apache Tiles, I have incorporated JavaScript libraries such as JQuery by including them in the pom.xml file as dependencies. My query pertains to whether I can access these scripts from within ...

Detect the "@" character through keyUp for the implementation of @mentions feature

I am currently working on implementing an @mention feature using Vue and Vanilla JS, but I am facing issues with targeting the "@" character specifically. Within my template: <trix-editor ref="trix" @keyup="listenForUser" ></trix-editor& ...

Javascript Select Element with No Options

I'm currently working on a <select> element that is being populated from an array using the following code snippet: <select id="selector" name="selector"</select> <button type=button onclick=populateSelect(states)>Click me1!</ ...

"Adding content to the DOM using AJAX, the data is showing up as plain text rather than formatted

As part of my project, I am working on incorporating data retrieved through an AJAX request into the DOM to be able to manipulate it further. However, I encountered an issue where the data displayed as a string instead of HTML when appended to the DOM. Bel ...

"Filtering a JSON File Based on Button Data Attributes: A Step-by-

I am working with a set of buttons that have specific data-map attributes as shown below: <button class="btn btn-default mapper" data-map="2015-11-13">Monday</button> <button class="btn btn-default mapper" data-map="2015-11-14">Tuesday&l ...

Unable to display image using EJS and Multer

While working on my node.js application, I encountered an issue with rendering the uploaded image file. I have successfully integrated multer to handle file uploads, and the images are being stored in the correct folder. However, when trying to display the ...

Get the MAC address of a client using Node.js

I have a project in progress that aims to help my home automation system recognize the presence of individuals at home by using their MAC addresses as identifiers. In my attempt to collect the MAC address of a client on my network, I utilized Nodejs along ...

Validating the existence of a file through HTTPS in Javascript

After attempting to retrieve the file using this code, I've encountered an issue - it works with HTTP requests but not HTTPS requests (which is what I require). function checkUrl(url) { var request = new XMLHttpRequest(); try { request.ope ...

Tips for sending PHP variables together with a Typeahead variable

I have simplified this code as much as possible. I have a typeahead variable that is functioning correctly. However, I also need to pass two unrelated variables $php_var1 and $php_var2 along with the typeahead variable. These PHP variables are initialized ...

Show a message on form submission rather than redirecting

I'm working on a simple sign-up form and I want to show a success message directly on the page instead of redirecting to another page after submission. Is it better to display the message as a pop-up, an alert, or just on the page itself? <form a ...

Fixing a JavaScript conflict between the parent theme and the child theme in WordPress

Recently, I created a customized child theme based on the Divi Theme, tailor-made for integration with Buddypress. Everything was going smoothly until I encountered a conflict involving the commenting buttons due to a script. In my theme, there is a JavaS ...

Instructions on how to insert a single parenthesis into a string using Angular or another JavaScript function

Currently, I am employing Angular JS to handle the creation of a series of SQL test scripts. A JSON file holds various test scenarios, each scenario encompassing a set of projects to be tested: $scope.tests = [ { "Date": "12/31/2017", "Project": ...

Transmit an array in a post request with Node.js using the application/x-www-form-urlencoded content type

After attempting to send a post request to an API with post parameters as an array, I encountered difficulties. Here is how it can be done using cURL: curl http://localhost:3000/check_amounts -d amounts[]=15 \ -d amounts[]=30 I then tried to ach ...

`Can you provide instructions on modifying CSS using JavaScript once the window size reaches a specified threshold?`

Is there a way to use JavaScript to automatically adjust the font size when the screen reaches 1050px? ...

Listener function triggered following its deletion on IE11

While developing a component that listens for clicks on the entire document, I encountered an issue with IE11. To demonstrate this problem, I created a few simple components. class App extends React.Component { constructor(props) { super(props); ...

Create dynamic connections between animated sprites using Three.js

I am attempting to insert lines between animated sprites, similar to the example provided. Despite trying various solutions, I have been unsuccessful in creating either a dynamic or static line between these animated sprites. Is it feasible to generate a d ...

Using AngularJS to filter JSON data

Greetings! I possess the following JSON data: $scope.Facilities= [ { Name: "-Select-", Value: 0, RegionNumber: 0 }, { Name: "Facility1", Value: 1, RegionNumber: 1 }, { Name: ...

Execute PHP script through jQuery request within the context of a Wordpress environment

I want to replicate a specific functionality in WordPress. In this functionality, jQuery calls a PHP file that queries a MySQL table and returns the result encapsulated within an HTML tag. How can I achieve this? <html> <head> <script ...