 <pre><code>var re = /(#{5})/; console.log ("&lt;foo&gt;\n&lt;bar&gt;\n#####&lt;foo&gt;\n#####&lt;bar&gt;".match (re)); console.log ("&lt;foo&gt;\n&lt;bar&gt;\nfoo&gt;\n&lt;bar&gt;".match (re)); </code></pre> <p>output:</p> <pre><code>[ '#####', '#####', index: 12, input: '&lt;foo&gt;\n&lt;bar&gt;\n#####&lt;foo&gt;\n#####&lt;bar&gt;' ] null </code></pre> <p>If it's optional the regexp fails when there's no match and if it fails it returns null.</p> <pre><code>&gt; /a/.exec("a") [ 'a', index: 0, input: 'a' ] &gt; /a/.exec("b") null &gt; "a".match(/a/) [ 'a', index: 0, input: 'a' ] &gt; "b".match(/a/) null </code></pre> <p>Also, don't use String#match(), it's slower than RegExp#exec() and both return the same:</p> <p><a href="http://jsperf.com/string-match-vs-regexp-test/3" rel="nofollow">match() vs exec()</a></p>