title: Match any url in Mongoose with or without http(s) or www
body: <p>What I'm trying to achieve is to find a way to verify if a URL already exists in a MongoDB document, without saving the URL twice, one with HTTP(s)(www) protocol, and other clean of HTTP(s)(www) to perform the match.
  For example, if the MongoDB document contains a record:</p>
  
  <pre><code>'url': "http://mysite.co?search=pattern&amp;co=43"
  </code></pre>
  
  <p>So, I want to perform a search:</p>
  
  <pre><code>MyCollection.find({'url': "mysite.co?search=pattern&amp;co=43"})...
  MyCollection.find({'url': "http://mysite.co?search=pattern&amp;co=43"})...
  MyCollection.find({'url': "https://mysite.co?search=pattern&amp;co=43"})...
  MyCollection.find({'url': "http://www.mysite.co?search=pattern&amp;co=43"})...
  MyCollection.find({'url': "https://www.mysite.co?search=pattern&amp;co=43"})...
  </code></pre>
  
  <p>The search should match with the URL actually saved in the document.</p>
  
  <p>I'm trying to use the following regex: </p>
  
  <pre><code>MyCollection.find({'url': new RegExp('^https?:\/\/(www.)?(' + 'mysite.co?search=pattern&amp;co=43' + ')+$', 'gim')})...
  </code></pre>
  
  <p>However, I'm not very clever creating regex expressions, and I still struggle with it. Seems that the question mark in the URL breaks the regex, and I'm not pretty sure if just using a replace from '?' to '\?' is the right way to go.</p>
  
  <p>The search must match 'exactly' the URL in the DB, except for the HTTP(s)(www) protocol. I mean, if the URL in the document contains other params:</p>
  
  <pre><code>'url': "http://mysite.co?search=pattern&amp;co=43&amp;other=more_params"
  </code></pre>
  
  <p>The search should not be matched this time.</p>
  
  <p>I'm using Mongoose and nodejs.</p>
  
  <p>Thanks in advance.</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Based on your answers, I have improved a little bit the regex and scaping for the URL:</p>
  
  <p>First, a function to trim and 'clean' the URL of HTTP(s) or (www):</p>
  
  <pre><code>String.prototype.url_clean = function() {
      return this.trim().replace(/^(http(s|):\/\/)?(www\.|)/g, '');
  };
  </code></pre>
  
  <p>And a function to escape the URL:</p>
  
  <pre><code>RegExp.escape = function(s) {
      return s.replace(/[-[\]{}()*+!&lt;=:?.\/\\^$|#\s,]/g, '\\$&amp;');
  };
  </code></pre>
  
  <p>So I can perform the search:</p>
  
  <pre><code>MyCollection.find({'url': new RegExp('^(http(s|):\/\/)?(www\.|)(' + RegExp.escape(url.url_clean()) + ')(|\s)+$', "gim")})
  </code></pre>