Retrieve the second occurrence of a regular expression match

I'm currently working on extracting the second occurrence in a regular expression string.

Let's consider a domain name:

https://regexrocks.com/my/socks/off

We want to replace everything after .com

$this.val($this.val().replace(/(([^.]*.)[^]?.[^\/]?)/, ''));

The regex being used is:

(([^.]*.)[^]?.[^/]?)

This will replace the first match with the second: /my/socks/off.

https://regex101.com/r/46BIqG/1

Is there a way to capture the second match instead?

Answer №1

The regex you are using replaces the first match with an empty string while keeping the rest of the original string intact.

Give this a try:

"https://regexrules.com/for/beginners".match(/(.*\.com)(.*)/);

This will give you an array of capture groups, with group 1 at index 1 and group 2 at index 2.

For example, to access group 1:

"https://regexrules.com/for/beginners".match(/(.*\.com)(.*)/)[1]; //https://regexrules.com

And to access group 2:

"https://regexrules.com/for/beginners".match(/(.*\.com)(.*)/)[2]; ///for/beginners

Answer №2

Instead of using replace(), try accessing index 0 of the result from a match():

url.match(/(([^.]*.)[^]?.[^/]?)/)[0]
// This should give you "https://regexrocks.com"

If you're dealing with URLs, you can also utilize an anchor tag <a> for a neat trick:

var url = document.createElement('a');
url.href = 'http://www.example.com/path/to/something';
console.log(url.origin); // Outputs "http://www.example.com"

For further information:

https://developer.mozilla.org/en-US/docs/Web/API/Location#Examples

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

Unknown provider in Angular when using factory inside anonymous function wrapper

I encountered an issue with an unknown provider error when using a factory and declaring it with an anonymous function: (function () { 'use strict'; angular.module('app').factory('errorCodeFactory', errorCodeFactory) ...

Is the npm mqtt module continuously running but not performing any tasks?

I'm relatively new to the world of JS, node.js, and npm. I am attempting to incorporate a mqtt broker into a project for one of my classes. To gain a better understanding of how it functions, I installed the mqtt module from npm. However, when I tried ...

Create an Angular service that outputs class properties as observables

I am trying to accomplish the following task: I have a component with a UserService in it. After a user logs in, I want to call this service to retrieve user data from the backend and store it in a service field. Then, when the main page is reloaded, I wan ...

A guide on assigning a state variable to a dynamically generated component within a React application

I need to display user data from an array and have a button for each watchlist that deletes it. Although the backend is set up with a function deleteWatchlist, I am facing an issue in setting the state of the watchlistName for each watchlist after mapping ...

Scrolling horizontally in a container using the mouse wheel

Is there a way to enable horizontal scrolling in a div using the mouse wheel or drag functionality with jQuery? I attempted using draggable, but it did not work effectively in my specific code scenario. Currently, I have a horizontal scrollbar. Are there ...

React-Native error message: Promise rejection unhandled - React child cannot be an object

I am experiencing an issue with rendering a list from an array of objects that have the structure provided below. While I have successfully handled the promise and set the data to the state, I keep encountering an error specifically with this array. The da ...

Having trouble submitting a form in React JS

I'm facing an issue with my form where I am trying to print the data in console upon submission, but for some reason it's not working. The form is not submitting and I can't figure out why. Below is the code I have written. Any help would be ...

Tips for creating a consistent format based on test cases

var years = Math.floor(seconds / (3600*24*365)) seconds -= years*3600*24*365 var days = Math.floor(seconds / (3600*24)) seconds -= days*3600*24 var hrs = Math.floor(seconds / 3600) seconds -= hrs*3600 var minutes = Math.floor(seconds / 60) ...

How can I find the week of the month using Moment.js? (similar to Google Calendar)

Currently leveraging the fantastic features of Moment.js, I am facing a dilemma. How can I determine which week of the month a particular date falls into? The documentation for Moment js only seems to provide information on "week of year." For instance, if ...

Vuetify input with appended button showing loader malfunction

One of the fields in my form is an email input with complex validation rules. I'm using Vuelidate for form validation, and once the user enters a valid email, I want to display a 'Check' button to verify if the user exists. While the server ...

Trouble arises when attempting to establish an isolated scope within Angular alongside UI Bootstrap

My table of data is set up with AngularJS, and one of the columns is calculated using a function in the controller. On my webpage, I have a button that opens a modal. When I use UI Bootstrap to open the modal, it creates a new isolated scope (child of the ...

Utilizing the URLSearchParams object for fetching data in React

I've implemented a custom hook named useFetch: const useFetch = (url: string, method = 'get', queryParams: any) => { useEffect(() => { let queryString = url; if (queryParams) { queryString += '?' + queryParam ...

Unable to locate the specified view within AngularJS framework

<!doctype html> <html lang="en" ng-app="phonecatApp"> <head> <script src="/js/angular-1.5.2/angular.js"></script> <script src="/js/angular-1.5.2/angular-route.js"></script> <script src="/js/app.js">< ...

Submitting multiple forms using AJAX and PHP

I am currently trying to send the form data to another page for processing, but I am not receiving any data. Below are the forms in question: The default form is the login form for requesting a username and password, with only one submit button. ...

Is there a way to adjust the contents of an iframe to match the dimensions of the iframe itself?

I am trying to adjust the width of an iframe to 60%, regardless of its height. Is there a way to "zoom in" on the contents of the iframe to fit the width, so that I can then set the height based on this zoom level? I haven't been able to find any solu ...

looping through an array to extract values

i have: var myVariable= { var_one: ["satu", 'uno'], var_two: ["dua", 'dos'], var_three: ["tiga", 'tres'], var_four: ["empat", 'cuatro'], var_five: ["lima", 'cinco'], var_six: ["enam ...

Ways to prevent other users from clicking or modifying a particular row

I have a data table in my project that will be accessed by multiple users simultaneously. My requirement is that once a row is selected and edited by one user, it should become unclickable for other users who are also viewing the same page or data table. ...

Issue with unrecognized expression in JQuery when processing Ajax response

Recently, I implemented a JQuery Ajax Form on my website. $('#modal-body-sign-in').on('submit', '#sign-in', function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr(&apo ...

Discover a corresponding object within an array

I am currently dealing with an array of objects in Javascript where I need to verify if a certain value exists within any object and return the corresponding id. The issue arises when using the some() function as it only seems to match the first object. T ...

Creating a Page with Python Selenium for JavaScript Rendering

When using Python Splinter Selenium (Chromedriver) to scrape a webpage, I encountered an issue with parsing a table that was created with JavaScript. Despite attempting to parse it with Beautiful Soup, the table does not appear in the parsed data. I am str ...