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 2.0KB

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