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

Guide to extracting information from a Node.js http get call

I am currently working on a function to handle http get requests, but I keep running into issues where my data seems to disappear. Since I am relatively new to Node.js, I would greatly appreciate any assistance. function fetchData(){ var http = requir ...

Transform the object into JSON while excluding specific (private) attributes

I recently started using dean edwards base.js for organizing my program into objects. I must say, base.js is truly amazing! But now I have a question that doesn't require prior knowledge of base.js to answer. Within one of my objects, I have a proper ...

How come my button is initiating automatically instead of manually?

Working on developing an API using Angular 2 with the Janus media server has brought up an issue regarding the start button. When running Janus, the button initiates automatically instead of manually. The following function was implemented for this purpos ...

Trimming content within an editable div in JavaScript: A guide

I am working on an editable div feature where users can input text for comments. My goal is to eliminate any unnecessary spaces before and after the text. For example, if a user types: "&nbsp;&nbsp;Hello&nbsp;world&nbsp;&nbsp;&nbsp ...

Joomla website experiencing issues with Bootstrap popover functionality

Just wanted to share that I am currently working on this page: I found an example that inspired me from here: I have a feeling that Joomla might be including a resource that is causing conflicts with the popover not showing. This is the code snippet I h ...

Parsing values from deeply nested objects and arrays

I've come across this issue before, but I'm having difficulty navigating through a nested structure. I can't seem to find any guidance in the right direction. Here is the object I'm attempting to parse: const nestedArray = { id ...

How can I make tooltipster display tooltips properly?

I have been struggling to customize tooltips using a library called tooltipster. Here is what I currently have: Head of index.html: <head> <!--TOOLTIP CSS--> <link rel="stylesheet" type="type/css" href="node_modules/tooltipster-master ...

Navigating with Angular - sending users to an external webpage?

When working with AngularJS routes, there is the option to use an otherwise route as a replacement for a 404 error: $routeProvider .when(...) .otherwise({ redirectTo: 'my/path' }); Is it possible to configure the otherwise route to redirect ...

React - Clearing State data retrieved from axios request

I am currently facing an issue with resetting the state of an object in my users array upon clicking the delete button. Even after successfully removing the object from the database, the state does not update as intended. I have managed to verify the prese ...

`Can you explain how to specify the elements of an array within a form using AngularJS?`

Below is an array containing objects: //Data source code $scope.data = [ { name: 'Lname', items: [{ label: 'Lastname', type: 'text', model: 'lname', pattern: '/^[a-zA-Z]$/', ...

Error message: The 'node_modules' directory is not found after installing

During class today, I faced a problem. I was demonstrating to my students how to install and use gulp.js using a projector. I successfully installed node.js and gulp.js globally with npm install -g gulp without any issues. However, when attempting to ins ...

Fixing the mobile display issue with react-responsive-carousel

I am relatively new to ReactJS and I am looking to develop a responsive Carousel. Here is the code snippet that I have currently: To achieve a responsive Carousel for both desktop and mobile devices, I utilized the react-responsive-carousel library. The ...

Encountering a runtime error in React while making an async call on a NextJS 13 page

I am currently working on implementing async calls using the new app layout in NextJS 13. I have been referring to the latest documentation page. However, I have encountered an error that I can't seem to resolve. Below is a snippet from my app/page.t ...

Sort columns in a MUI datatable

I am facing an issue with sorting in a column that represents an object. Although I can display the desired value, the sorting functionality does not seem to work for that particular column. Here is an example to provide better clarity: const [data, set ...

Configuring the baseUrl for Axios in a Vue.js application triggers the sending of a request

I have encountered an issue in my app where Axios automatically makes a request to the baseUrl without me explicitly making one. This occurs even when the app is loaded in the browser. In my main.js file, I have set the baseUrl using: axios.defaults.baseU ...

Enhance your website with jQuery's animate() feature for dynamic

My current implementation of jQuery's animate function looks like this: var css1 = { display: "block", marginTop: 20 }; var direction = "marginTop"; $(element).animate(css1, 150, 'swing'); I've noticed the marginTop ...

Unanticipated Behavior in JavaScript (jQuery): Triggering a Function Instead of Submitting a Form

I'm confused about something. Here's my issue: I have a specific type of form declaration where jQuery processes the form data and sends an Ajax request. Inside the form, there are buttons - one for form submission (Ajax) and another for calling ...

How can we process the incoming data that is in a JSON format?

I'm in the process of creating a Zap that collects customer feedback through Unbird and delivers a coherent Slack message that can be easily understood by anyone within my organization. When importing customer feedback data from Unbird into Zapier, i ...

Extracting data from websites by manipulating the Document Object Model with the help of Javascript and Ajax

Currently, I am in search of data for educational purposes from a website. Specifically, the website focuses on statistics in web development. The challenge lies in the fact that this particular site uses Javascript/Ajax to constantly update numbers. I w ...

Writing and altering content within the <code> element in Chrome is unreliable

Utilizing a WYSIWYG Editor with contenteditable functionality allows users to input "code snippets" using a <code> element. Here is an example: <div contenteditable="true"> <p> This is a paragraph with an <code>inline s ...