Using regular expressions, you can locate and replace the second-to-last instance of a dot character in an email address

I'm looking to replace the second last occurrence of a character in a given string. The length of the strings may vary but the delimiter is always the same. Here are some examples along with my attempted solutions:

Input 1: james.sam.uri.stackoverflow.com

Output 1: [email protected]

Input 2: noman.stackoverflow.com

Output 2: [email protected]

Input 3: queen.elizabeth.empire.co.uk

Output 3: [email protected]

My approach:

//Although this solution works, I am looking for a regex solution
const e = "noman.stackoverflow.com"
var index = e.lastIndexOf(".", email.lastIndexOf(".")-1)
return ${e.substring(0,index)}@${e.substring(index+1)}

Regex:
e.replace(/\.(\.*)/, @$1)
//This regex solution only works for Input 2 and not Input 1. I need a regex that can handle both cases, as it currently only matches the first dot.

Answer №1

The challenge with the provided data example involving the second-to-last dot is that it concludes with .co.uk

To address this issue in similar cases, one approach could be to employ a specific pattern that excludes that particular segment.

(\S+)\.(?!co\.uk$)(\S*?\.[^\s.]+)$
  • (\S+) Grouping 1: capturing and matching one or more non-whitespace characters
  • \.(?!co\.uk$) Matching a period followed by a negative lookahead assertion ensuring it's not immediately succeeded by "co.uk"
  • ( Grouping 2:
    • \S*?\. Matching zero or more non-whitespace characters non-greedy, followed by a period
    • [^\s.]+ Matching at least one non-whitespace character excluding periods
  • ) Closing group 2
  • $ Denoting the end of the string

For reference, check out the demonstration on regex101.

[
  "james.sam.uri.stackoverflow.com",
  "noman.stackoverflow.com",
  "queen.elizabeth.empire.co.uk"
].forEach(s =>
  console.log(s.replace(/(\S+)\.(?!co\.uk$)(\S*?\.[^\s.]+)$/, "$1@$2"))
);

Answer №2

Here is an alternative method to tackle this:

(\S+)\.(\S+\.\S{3,}?)$
       (            )$  To capture at the end of the string,
             \S{3,}?    match lazily 3 or more non-whitespace characters
        \S+\.           along with any non-whitespace characters preceded by a period.
(\S+)\.                 Additionally, capture anything before the period separator.

This approach may not work for email formats like test.stackoverflow.co.net. If such a format is required, it's advisable to consider a different strategy.

[
  "james.sam.uri.stackoverflow.com",
  "noman.stackoverflow.com",
  "queen.elizabeth.empire.co.uk",
  "test.stackoverflow.co.net"
].forEach(s =>
  console.log(s.replace(/(\S+)\.(\S+\.\S{3,}?)$/, "$1@$2"))
);

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

Issue: Reactjs - Material-UI HTML Tooltip does not display dynamic HTML content.In the Reactjs

I have been using a customized HTML MUI Tooltip. Currently, it is functioning with static content but I am looking to make it dynamic. Unfortunately, it is not working with dynamic HTML content. Here is my attempted approach: const ADJUSTMENT_HELP_TEXT = ...

Error: It is not possible to assign a value to the Request property of the Object since it only has a getter method

Encountering issues while attempting to deploy my Typescript Next.js application on Vercel. The build process fails despite functioning correctly and building without errors locally. Uncertain about the root cause of the error or how to resolve it. The f ...

Convert the existing jQuery function to Angular 9 syntax

I have just started learning Angular and am finding it challenging to rewrite a jQuery code that I use for loading the "classycountdown" script. Below is the jQuery function that I need to convert: $(document).ready(function() { var remainingSec = $(& ...

Spinner displayed upon task completion

Currently, I am developing a project using Spring Boot. I would like to display a spinner on my page to indicate that a task involving heavy calculations is in progress. Even though the page may take up to 5 minutes to load, my spinner only appears for t ...

When clicking in JavaScript, there are two parts to the function, however only one part will work at any given time

I am currently working with two server-side PHP scripts: 1. /addit.php - which generates a PDF file on the server based on the provided ID 2. /viewit.php - which allows the PDF file to be downloaded to the browser window. While both of these scripts are ...

The transitionend event fails to trigger if there is no active transition taking place

Take a look at this: http://jsfiddle.net/jqs4yy0p/ JS $('div').addClass('switch').on('transitionend', function(e){ alert('end'); }); CSS div { background-color: red; /*transition: background-colo ...

The functionality of the Hubot script is restricted to Slack conversations where I initiate a direct message with the

At this very moment, my automated Hubot assistant is functioning properly. When I send the following message via direct message to the robot in Slack: qbot !npm bower The response provided by the robot contains a link: https://www.npmjs.com/package/bowe ...

An interface that is extended by an optional generic parameter

I currently have an exported abstract class that has one generic. However, I now require two generics. I do not want to modify all existing classes that are using this class. Therefore, I am looking to add an optional generic class that extends an interfac ...

Error message: Cannot establish the attribute 'next' on the string '/:id'

I encountered an error while trying to develop an API for a travel company. The error message "TypeError: Cannot create property 'next' on string '/:id'" keeps popping up, even though all the necessary functions are already created. con ...

Exploring the location.path in angularjs

Is there a way to use $location.path for redirection in angularjs? I have the configuration below: ngModule.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { $urlRouterProvider. ...

What is the best way to dynamically incorporate Before After CSS code in Vue?

I am facing a unique challenge in my current project. I need to dynamically apply colors from data inside a v-for loop, specifically for the :after CSS pseudo-element. While normal CSS properties are easily applicable, I am struggling with applying styles ...

The React engine is triggering an error stating "Module not found."

Utilizing react-engine to enable the server with react component access. Through react-engine, you can provide an express react by directing a URL and utilizing res.render. The documentation specifies that you need to supply a path through req.url. app.use ...

Reached the maximum number of iterations for Angular 10 $digest() function

Currently, I am following a MEAN stack tutorial on Thinkster and encountering an issue with my Angular factory service. Angular.js:11598 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! Watchers fired in the last 5 iterations: [] H ...

The exploration of child routes and modules

I'm currently working on a somewhat large project and I've decided to break it down into modules. However, I'm facing an issue with accessing the routes of admin.module.ts. In my app.module, I have imported the admin Module. imports: [ Br ...

Reset dropdown selection when a search query is made

Currently experimenting with Angular to develop a proof of concept. Utilizing a functional plunker where selecting an option from a dropdown populates a list of items from an $http.get( ). Additionally, there is a search input that should trigger its own $ ...

Incorporate a line break into a document using JavaScript

Is there a way to make all the items inside document.get on new lines without using paragraph elements? I have tried br/ and \n, but they do not work as expected. They either cause issues with JavaScript execution or fail to create new lines. <scr ...

Creating mock implementations using jest in vue applications

I have been experimenting with testing whether a method is invoked in a Vue component when a specific button is clicked. Initially, I found success using the following method: it('should call the methodName when button is triggered', () => { ...

Obtain a string of characters from different words

I have been trying to come up with a unique code based on the input provided. Input = "ABC DEF GHI" The generated code would look like, "ADG" (first letter of each word) and if that is taken, then "ABDG" (first two letters o ...

The subscription for the second Observable in RxJS concatMap is triggered individually

I am currently developing an Angular 6 application. I want the app to display a loading animation whenever there is a change in the route or if there are any pending HTTP requests. To achieve this, I have set up two Observables as follows: For httpPendingR ...

Customize URL based on selected button

My question may be a bit unclear, but I want to generate dynamic URLs that redirect users to specific pages based on the link clicked. For example: Parent page with links (a, b, c, x, y) User clicks on 'b' User is taken to a Node Page that play ...