Advertisement
Guest User

Untitled

a guest
Sep 11th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. import { Injectable } from '@angular/core';
  2. import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
  3.  
  4. interface FormatterPatternAndReplacement {
  5. pattern: RegExp;
  6. replacement: string;
  7. }
  8.  
  9. @Injectable()
  10. export class Formatter {
  11. // define your characters
  12. static asCode = new RegExp(/`(.*?)`/g);
  13. static asPre = new RegExp(/`{3}(.*?)`{3}/);
  14. static asBold = new RegExp(/\*(.*?)\*/g);
  15. static asItalic = new RegExp(/_(.*?)_/g);
  16. static asStrikeThrough = new RegExp(/~(.*?)~/g);
  17. static allSupportedMatchers = new RegExp(/`(.*?)`|\*(.*?)\*|_(.*?)_|~(.*?)~/g);
  18.  
  19. static formatters: FormatterPatternAndReplacement[] = [
  20. {pattern: Formatter.asItalic, replacement: 'i'},
  21. {pattern: Formatter.asCode, replacement: 'code'},
  22. {pattern: Formatter.asBold, replacement: 'b'},
  23. {pattern: Formatter.asStrikeThrough, replacement: 'del'}
  24. ];
  25.  
  26. constructor(protected sanitizer: DomSanitizer) {}
  27.  
  28. stripFormattersAndReturnHTML(textToFormat: string, tag): string {
  29. return `<${tag}>${textToFormat}</${tag}>`;
  30. }
  31.  
  32. sanitizedOutput(formattedText: string): SafeHtml {
  33. return this.sanitizer.bypassSecurityTrustHtml(formattedText);
  34. }
  35.  
  36. processword(word: string): string {
  37. return Formatter.formatters.reduce(
  38. (word, formatter) => word.replace(formatter.pattern, (match, enclosed) => {
  39. return `<${formatter.replacement}>${enclosed}</${formatter.replacement}>`;
  40. })
  41. , word);
  42. }
  43. formatText(text: string): SafeHtml {
  44. if (text.indexOf('```') > -1) {
  45. if (text.replace('```', '').indexOf('```') > -1) {
  46. const decoded = text.replace(Formatter.asPre, (match, enclosed) => enclosed)
  47. .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
  48. .replace('```', '').replace('```', '');
  49. return this.sanitizedOutput(`<pre>${decoded}</pre>`);
  50. }
  51. }
  52. return this.sanitizedOutput(this.processword(text));
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement