1

I want to replace every kind of url with a * (www, http, https bla.bla.com etc.) There is just one case I want to allow, which is "www.google.com, google.com or http://google.com etc.)

I've got this but don't know how to write it to the wanted value

var urlCheck = new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?");

Any ideas?

1
  • 1
    Create an exception list. Then create a generic regex to replace. Then match if this url is in exception list, if yes return, else replace and then return Commented Jan 3, 2016 at 4:32

1 Answer 1

2

Simply place the things you don't want to match as alternatives at the beginning, and don't capture them.

var urlCheck = new RegExp("(?:w+\.)?google\.com|([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?");
                           ^^^^^^^^^^^^^^^^^^^^ Match google, don't capture

Results:

< "hello bob www.numenware.com foo www.google.com bar".replace(urlCheck, "*")

> "hello bob * foo www.google.com bar"

The ?: specifies a non-capturing group.

Read more here.

If you would prefer to handle the exceptions separately then

var blacklist = /(\w+\.)?google\.com/;

string.replace(urlCheck, function(match) { return blacklist.test(match) ? match : "*"; });

This has the advantage of making the blacklist easier to manage and update without having to edit the main regexp itself.

Sign up to request clarification or add additional context in comments.

4 Comments

Any reason for using the constructor rather than a RegExp literal?
Because the OP did. But using a literal is better of course.
@torazaburo, just a curious question. Which one is a better approach, having a list of exception with generic regex, or using a regex with exceptions in itself?
@Rajesh I don't think there are any strong grounds for preferring one over the other. Perhaps the list of exceptions is slightly more maintainable. See updated answer. However, it is still worth learning the technique shown in the first answer.

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.