Advertisement
Guest User

単語表で置換

a guest
Sep 10th, 2013
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var list = "apple, りんご, orange, みかん, orangejuice, おれんじじゅーす";
  2. // ↑をカンマ区切りで設定してね
  3.  
  4. var dict = list.split(/\s*,\s*/);
  5. if (dict.length % 2 != 0) { throw new Error("単語数が奇数になってる"); }
  6. for (var i = 0; i < dict.length / 2; i++) { dict[i] = [dict[i * 2].replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), dict[i * 2 + 1]]; }
  7. dict.length /= 2;
  8. dict.sort(function(a, b) { return b[0].length - a[0].length; });
  9. if (document.selection.Text == "") { document.selection.SelectAll(); }
  10. var text = document.selection.Text;
  11. for (var i = 0; i < dict.length; i++) { text = text.replace(dict[i][0], dict[i][1]); }
  12. document.selection.Text = text;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement