Using Javascript to parse a regular expression in a string

I am facing a challenge with a JavaScript string that contains contact information that needs to be filtered. For example, I want to mask any email or phone number in the message.

I have attempted the following approach:

function(filterMessage) {
            var maskedMessage = filterMessage.replace("/^([\da-z_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/", "<MaskedEmail>");
            return maskedMessage;
        }

Unfortunately, this method is not producing the desired results.

Answer №1

Give this a shot:

function sanitizeEmail(message) {
        var m = message.replace(/[\da-z_\.-]+@[\da-z\.-]+\.[a-z\.]{2,6}/, "<Email>");
        return m;
    }


alert(sanitizeEmail("Your Email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="39827e93878b8c978687808fce85889386">[email protected]</a> lorem Ipsum dolor"));

See the demo here: http://jsfiddle.net/abcd1234/

Issues to address in your code:

  • Missing function name
  • Remove extra quotation marks from the Regular Expression

Answer №2

I like to employ a more lenient regex pattern when searching for email addresses because of the various formats they can take. One example you could try is:

/\S+@\S+\.\S+/   

This regex will match [email protected], where any non-whitespace characters can be used instead of a, b, and c.

Feel free to use this alternative regex in place of the one suggested by strah's recent answer.

Answer №3

Give this a shot:

function modifyText(text) {
    //var reg = /^([\da-z_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
    var regExp = /\b(\S+@\S+\.\S+)\b/g;
    var modifiedText = text.replace(regExp, "<Email>");
    return modifiedText;
}

modifyText("email.example.com will be substituted, and so will be <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98f6fde0ecd8fde0f9f5e8f4fdb6fbf7f5">[email protected]</a>");

Alternatively, you can try using this regular expression: /\b(\S+@\S+\.\S+)\b/g (taken from Kieran Pot's response) and then apply your function for more accurate filtering.

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

Regular expression in Python

I need help creating a Python 2.7.8 regex statement to replace certain characters. The substitutions should be as follows... ó -> o ú -> u é -> e á -> a í -> i ù,ú -> u These specific unicode characters need to be changed, while ...

Execute the function when the element comes into view

Is there a way to create a function that will automatically attach itself to an element when it comes into view? I have multiple elements on my page - element1, element2, and element3. Instead of using a large if statement, I would like to write a functio ...

Is it possible to avoid sending multiple $http requests in Angular? Are there more efficient methods available?

I have developed a rather intricate method for retrieving resources using $http. This method returns a promise and first checks my local cache to see if the resources are already available. If they are, it will return the cached data; if not, it will make ...

"Exploring the process of comparing dates using HTML, AngularJS, and Ionic

I am working on an HTML file that shows a list of notification messages. I am trying to figure out how to display the time difference between each notification. The code snippet below displays the notifications and includes the time for each one: <ion- ...

encountering an issue with the react hook useHistory leading to an error

I recently encountered an issue while implementing useHistory() in my code. Previously, I had used it without any errors, but now I'm getting the following error in this component: Line 6:18: React Hook "useHistory" is called in function "showPost" ...

Deployment replacement in Kubernetes encounters error

I've developed a NodeJS script to deploy review apps to Kubernetes for my GitLab repository, using the Kubernetes NodeJS client. Including abbreviated definitions of Kubernetes resources for thoroughness: const k8s = require('@kubernetes/client ...

Exploring techniques for creating realistic dimensions in CSS

My goal is to create a responsive website that accurately displays an object with specified dimensions, such as a width of 100mm, regardless of the user's screen resolution. However, I am facing challenges in achieving this consistency across all devi ...

Problems with Searching in Bootstrap Tables

I'm experiencing a basic bootstrap error. I attempted to create a searchable table using this example: Unfortunately, the search function is not working when applied to my table. The table appears fully populated, but entering search terms like "CRY" ...

Engaging with JSON data inputs

Need help! I'm attempting to fetch JSON data using AJAX and load it into a select control. However, the process seems to get stuck at "Downloading the recipes....". Any insights on what might be causing this issue? (Tried a few fixes but nothing has w ...

Tips for extracting a website's dynamic HTML content after AJAX modifications using Perl and Selenium

When dealing with websites that utilize Ajax or javascript to display data, I'm facing a challenge in saving this data using WWW::Selenium. Although my code successfully navigates through the webpage and interacts with the elements, I've encounte ...

navigate back to the previous tab using protractor

When I open a new tab (second), I attempt to switch back to the first tab. common.clickOpenNewSession(); //opens a new tab browser.getAllWindowHandles().then(function (handles) { var secondWindowHandle = handles[1]; var firstWindowHandle ...

The asynchronous function is not being executed by onSubmit

I am attempting to create a function that will generate a gif when the "get gif" button is pressed. However, I am facing an issue where nothing shows up in the console and the page reloads. 1) The requirement is for the client to enter a value 2) Set th ...

The function setState() is not performing as expected within the useEffect() hook

After retrieving data from my Mongo database, it's returned as an object within the useEffect hook function, specifically in the response. I then initialize a state called myorders with the intention of setting its value to the data fetched from the A ...

Having trouble uploading Node.js and Mongoose to Heroku due to error codes H12 and H15? Need help troubleshooting and resolving this issue?

Attempting to deploy my Node, mongoose, express app on Heroku for the first time has been a challenge. The application is a simple blog with a login system. Despite extensive research and effort, I am struggling to successfully host it. Below is the error ...

Navigate to a different page using Angular2 routing

Looking for guidance on using redirect in the new Angular 2 router. Specifically interested in examples similar to 'redirectTo' from the beta version. Any demos on 'plnkr.co' would be greatly appreciated! ...

I am attempting to utilize the fetch API method to initialize the store's state, but for some reason, it is not functioning properly

Within my store.js file, I have a state called user_data, with its initial method set to fetch_user_data: export default new Vuex.Store({ state: { user_data: util.fetch_user_data('username') ... } located in the util.js file: util. ...

Creating a dynamic menu structure by tailoring it to the specific elements found on each page

Currently, I am facing issues while attempting to generate a dynamic menu based on the elements present on the page. Is there a way to develop a menu using the following code structure?: <div class="parent"> <div class="one child" id="first"& ...

Having trouble with Angular's ng-class performance when dealing with a large number of elements in the

I've encountered a performance issue while working on a complex angular page. To demonstrate the problem, I've created a fiddle that can be viewed here. The main cause of the performance problem lies in the ng-class statement which includes a fu ...

Encountering issues with webpack module federation and single-spa-vue integration, specifically with Vue version 2.16.12

I'm currently facing an issue while developing a microfrontend using single-spa-vue and Vue 2.6.12. To set up my project, I am utilizing the webpack module federation plugin. Below is the entry point for my application: src/app.ts import singleSpaV ...

Tips for incorporating Vue.js tag attributes in IDEA

I am using IDEA 2016.2.5 and I'm trying to incorporate Vue.js into my project. However, Vue has some tag attributes that IDEA is not recognizing and keeps highlighting as errors. I have installed the Vue Plugin and tried setting the HTML custom unkno ...