title: How to replace and shorten hyperlinks in a paragraph of text with JavaScript/jQuery?
body: <p>Say I have a paragraph of text:</p>
  
  <pre><code>The Northrop Grumman X-47B https://en.wikipedia.org/wiki/Northrop_Grumman_X-47B 
  is a demonstration unmanned combat air vehicle (UCAV) designed for carrier-based 
  operations.
  </code></pre>
  
  <p>I want to replace the hyperlink within the text and turn it into a real hyperlink. At the same time I want to shorten the wording of the hyperlink to a fixed 20 characters so the text the user would read is shorter e.g. </p>
  
  <ul>
  <li>The Northrop Grumman X-47B <a href="https://en.wikipedia.org/wiki/Northrop_Grumman_X-47B" rel="nofollow noreferrer">https://en.wikipedia.org...</a> is a demonstration unmanned combat air vehicle (UCAV) designed for
  carrier-based operations.</li>
  </ul>
  
  <p>So the code of the link within the text might look like this:</p>
  
  <pre><code>&lt;a href="https://en.wikipedia.org/wiki/Northrop_Grumman_X-47B"&gt;https://en.wikipedia.org...&lt;/a&gt;
  </code></pre>
  
  <p>I have had a look around and found a <a href="https://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links">few examples</a> but they don't work at all. I would like just a standard JavaScript function to do it. That is, a function which takes in plaintext (not HTML) and can convert the text. Not sure how you would protect against XSS at the same time.</p>
  
  <p>I have a suspicion it will involve a combination of looping through each part of the text, then some regex to find the URL, extract it, then shorten the URL with substr() then replace it into the text somehow. Any idea how to do it?</p>
  
  <p>Thanks for the help.</p>