textarea 内で、入力とともに強調表示を行うカスタム要素(HIGH-LIGHT)を作成しました。まだ、日本語入力やスマホへの対応が不十分なので用途を限定した使い方しかできません。あらゆるケースに対応するにはまだまだ時間がかかりそうです。
/* * Highlight keywords. * * s: input string * k: array of keywords * c: class name for css * */ var highlighting = function(s, k, c) { k.sort(function(a, b) { if (a < b) return 1; if (a > b) return -1; return 0; }).forEach(function(x) { s = s.replaceAll(x, `\x02${x}\x03`); }); s = s.replace(/\x02/g, `<span style="${c}">`); s = s.replace(/\x03/g, `</span>`); return s; }; jQuery(function($) { var k = [ '趙高', '王莽', '周伊', '禄山', '将門', '純友', '義親', '信頼', '清盛' ]; var d1 = document.querySelector('high-light#D1'); d1.highlight = function(html) { return highlighting(html, k, 'background-color:yellow;color:red'); }; var d2 = document.querySelector('high-light#D2'); d2.highlight = function(html) { const s = this.un_esc_html(html); const s1 = s.match(/^\s*/)[0]; const s2 = s.match(/\s*$/)[0]; const pre = new JSParser().parse(s); return s1 + $(pre).html() + s2; }; $('form').on('submit', function() { $('input[name=T1]').val(d1.value); $('input[name=T2]').val(d2.value); }); });