You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Replacement.js 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { regexes } from './smileys';
  2. /**
  3. * Processes links and smileys in "body"
  4. */
  5. export function processReplacements(body) {
  6. // make links clickable + add smileys
  7. return smilify(linkify(body));
  8. }
  9. /**
  10. * Finds and replaces all links in the links in "body"
  11. * with their <a href=""></a>
  12. */
  13. export function linkify(inputText) {
  14. let replacedText;
  15. /* eslint-disable no-useless-escape, max-len */
  16. // URLs starting with http://, https://, or ftp://
  17. const replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  18. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>');
  19. // URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  20. const replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  21. replacedText = replacedText.replace(replacePattern2, '$1<a href="https://$2" target="_blank" rel="noopener noreferrer">$2</a>');
  22. // Change email addresses to mailto: links.
  23. const replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  24. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  25. /* eslint-enable no-useless-escape */
  26. return replacedText;
  27. }
  28. /**
  29. * Replaces common smiley strings with images
  30. */
  31. function smilify(body) {
  32. if (!body) {
  33. return body;
  34. }
  35. let formattedBody = body;
  36. for (const smiley in regexes) {
  37. if (regexes.hasOwnProperty(smiley)) {
  38. formattedBody = formattedBody.replace(regexes[smiley],
  39. `<img class="smiley" src="images/smileys/${smiley}.svg">`);
  40. }
  41. }
  42. return formattedBody;
  43. }