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

Change the state within the click event handler

One issue I'm facing is dealing with 2 submit buttons in my react form. To differentiate between the two buttons, I need to extract the `id` of the one that was clicked using the `onClick` function. Currently, when trying to set the state with this ` ...

Tips for retrieving a variable from an XML file with saxonjs and nodejs

I came across an xml file with the following structure: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE agent SYSTEM "http://www.someUrl.com"> <myData> <service> <description>Description</description> < ...

Issue with Moment Js: Unable to change date with time zone function

Trying to convert a UTC date and time to local time ("Europe/Paris") using moment's timezone function, but encountering issues. The code I am using is: var m = moment.tz(this.startTime, 'Europe/Paris'); this.startTime = m.format("YYYY-MM-DD ...

Automatically navigate to a specific element as the user scrolls down the page

I am attempting to achieve a similar effect as seen on the App Builder Website. When the user reaches the header with the background image/video and scrolls down, the website smoothly transitions to the next div/section. If the user scrolls back up and ret ...

Unable to deploy Azure App Service due to difficulties installing node modules

My Azure Node.js App Service was created using a tutorial and further customization. The app is contained within one file: var http = require("http"); //var mongoClient = require("mongodb").MongoClient; // !!!THIS LINE!!! var server = http.createServer(f ...

Autoformatting files with ESLint on save

I'm encountering an issue where Visual Studio Code is saving my file in violation of the rules specified in my eslint configuration when using eslint and prettier for formatting. module.exports = { env: { browser: true, es2022: true, nod ...

Comparing timestamps in JavaScript and PHP - what are the discrepancies?

I seem to be having an issue with the inconsistency in count between two timestamps. Upon page load, I set the input value as follows: $test_start.val(new Date().getTime()); //e.g. equal to 1424157813 Upon submitting the form via ajax, the PHP handler sc ...

Standardize API response using NgRX Entity

Can the NgRx Entity library normalize a nested JSON api response? If I have data structured like this: [ { "id": "1", "title": "My first post!", "author": { "id": "123", "name": "Paul" }, ...

Error Message: Undefined Constructor for Firebase Google Authentication

Hey there! I've been working on integrating Firebase google authentication into my project. Unfortunately, I encountered an error while testing it out. Here's the error message that appeared in the console: Uncaught (in promise) TypeError: Cannot ...

Issue with combining jQuery-UI and Bootstrap offcanvas components

I've been struggling to understand why my Bootstrap navbar isn't working properly with jQuery-UI. It seems like they're not cooperating, and I can't seem to figure out the issue. If you have any insight into this problem, you'll be ...

Having Trouble Sending Text to InputBox Using Selenium WebDriver

Greetings everyone Can someone guide me on how to use Selenium to input a Login and Password in an Alert Dialog Box? Upon loading the webpage, the alert is already displayed: https://i.stack.imgur.com/F1O5S.png I have attempted the following code: Str ...

Building a personalized payment experience using Python Flask and Stripe Checkout

I'm attempting to set up a customized checkout integration with Stripe on my Flask web application and I've encountered some issues. After copying the code from the Stripe documentation (located at https://stripe.com/docs/checkout#integration-cu ...

Exploring the world of shaders through the lens of Typescript and React three fiber

Looking to implement shaders in React-three-fiber using Typescript. Shader file: import { ShaderMaterial } from "three" import { extend } from "react-three-fiber" class CustomMaterial extends ShaderMaterial { constructor() { supe ...

Encountering a MappingInstantiationException in MongoDB when attempting to modify a collection containing an abstract class

I've encountered a situation where I am using a single collection to store various classes that inherit from the same abstract class and are wrapped in another class. While I can successfully insert these records, updating a common property poses an i ...

Exploring the implementation of useMediaQuery within a class component

Utilizing functions as components allows you to harness the power of the useMediaQuery hook from material-ui. However, there seems to be a lack of clear guidance on how to incorporate this hook within a class-based component. After conducting some researc ...

What is the appropriate time to end a connection in MongoDB?

Utilizing Node.js Express and MongoDB for my API, I encountered an issue with the mongoClient connection. The data fetching process worked smoothly at first, but without refreshing it threw an error stating "Topology is closed." const express=require("e ...

What is the best way to transform this JSON data into an array of key-value pairs in JavaScript?

Dealing with nested JSON data can be challenging, especially when trying to extract key-value pairs efficiently. If anyone has suggestions on how to simplify this process and improve readability, please share your insights. The goal is to transform the ne ...

Creating an HTML Canvas using an AngularJS template

I am facing an issue with rendering html elements on a canvas using html2canvas JS. I am utilizing AngularJS for data binding on the html page, but unfortunately, the dynamic data is not showing up on the canvas generated from these html elements. For inst ...

Navigating from the Login Page to the Dashboard in Vue.js following successful token validation

I am facing an issue with the code that is supposed to redirect the User to the dashboard page if they have a token. Despite generating a JWT token from my Spring Boot backend and sending it to Vue for processing, the redirection is not working as expect ...

Animating HTML 5 canvas with keydown events

As a newcomer to programming, I've been experimenting with HTML 5 and canvas. My goal is to make a simple rectangle move when a key is pressed, but I'm facing difficulties in achieving this. I tried following the instructions provided in this gui ...