 <p>You may want to trim the string first, to avoid leading and trailing hyphens.</p> <pre><code>function hyphenSpace(s){ s= (s.trim)? s.trim(): s.replace(/^\s+|\s+$/g,''); return s.split(/\s+/).join('-'); } </code></pre>