1

I have a javascript string with some contact information I would like to filter. In example, if an email or phone is written, these should be replaced with a mask.

I´m trying to do something like:

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

but this is not working.

1
  • Is your question about the function above or the regular expression to do the task? Please define "not working". Commented Jul 9, 2015 at 16:30

3 Answers 3

1

You may try this:

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


alert(filterMessage("Your Email: [email protected] lorem Ipsum dolor"));

Working fiddle here: http://jsfiddle.net/ochxdkam/

Issues with your script:

  • No function name
  • Regular Expression in ", must be without
Sign up to request clarification or add additional context in comments.

Comments

1

I prefer to use a very loose regex to search for email addresses, because there are so many variations in how email addresses are formatted. You might try, for example:

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

This will match [email protected] where one or more non-whitespace characters are allowed in place of a, b, and c.

You could use this in place of the regex in strah's answer, just posted.

1 Comment

I have used OP's regex :-)
1

Try this:

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

filterMessage("email.example.com will be replaced, so will be [email protected]");

or you could use this regExp: /\b(\S+@\S+\.\S+)\b/g (from Kieran Pot's answer) and then you could use your function to do a little better filtering.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.