Advertisement
Guest User

Untitled

a guest
Dec 11th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. const escapeRegex = (string) => {
  2. return string.replace(/([^a-zA-Z0-9])/g, s => `\\${s}`);
  3. }
  4.  
  5. // will return a valid HTML string.
  6. const highlight = (s, t) => {
  7. s = escapeForHTML(s)
  8. t = escapeForHTML(t)
  9. const regex = new RegExp("(" + escapeRegex(t) + ")", "ig")
  10. return s.replace(regex, str => `<strong class='color-autocomplete'>${str}</strong>`);
  11. }
  12.  
  13. const escapeForHTML = (text) => {
  14. var escaped = '';
  15.  
  16. for (var i = 0; i < text.length; i++) {
  17. const code = text.charCodeAt(i);
  18. const char = text.charAt(i);
  19. const matches = char.match(/^[a-zA-Z0-9]$/);
  20.  
  21. /* don't escape alphanumerical chars */
  22. if (code >= 256 || (Array.isArray(matches) && matches.length === 1)) {
  23. escaped += char;
  24. continue;
  25. }
  26.  
  27. escaped += '&#x'+code.toString(16).padEnd(2, '0')+';';
  28. }
  29.  
  30. return escaped;
  31. }
  32.  
  33. document.body.innerHTML = highlight("Cadre de sécurité opposable juridiquement", "Cadre")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement