Skip to content

Instantly share code, notes, and snippets.

@nurse
Created January 7, 2009 04:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nurse/44169 to your computer and use it in GitHub Desktop.
Save nurse/44169 to your computer and use it in GitHub Desktop.
/* 強調タグを追加 */
function emphasizeWord(word) {
return '<strong>' + word + '</strong>';
}
/* 長い順に並べるための比較関数 */
function compareLengthDecrease(a, b) {
a = a.length;
b = b.length;
return a > b ? -1 : a < b ? 1 : 0;
}
/**
* 文章内を特定の単語で検索し、一致した部分を強調表示タグで置き換えます
* @param {String} searchWord 探索する単語
* @param {String} plainText 探索を行う文章
* @param {String} regexpType 正規表現の検索モードを示す文字列
*/
function complexEmphasize(searchWord, plainText, regexpType) {
// 正規表現の選択を長い順に並び替える
searchWord = searchWord.split('|').sort(compareLengthDecrease).join('|');
// タグの内側でないことを確認する正規表現を追加
var pattern = new RegExp(searchWord + '(?![^<>]*>)', regexpType);
var result = [];
var currentIndex = -1; // 現在マッチしている部分文字列の開始位置
var currentLastIndex = -1; // 現在マッチしている部分文字列の、現在の末尾
var m; // 正規表現マッチの結果配列
while (m = pattern.exec(plainText)) {
if (m.index > currentLastIndex) {
// 新しい部分文字列へのマッチが始まったので、そこまでの文字列をバッファに書き出す
if (currentIndex < currentLastIndex)
result.push(emphasizeWord(plainText.substring(currentIndex, currentLastIndex)));
result.push(plainText.substring(currentLastIndex, m.index));
// 開始位置の更新
currentIndex = m.index;
}
// 末尾位置を更新
currentLastIndex = pattern.lastIndex;
// 次の正規表現マッチは今マッチした文字の次の文字から
pattern.lastIndex = m.index + 1;
}
// 残った文字列を書き出す
if (currentIndex < currentLastIndex)
result.push(emphasizeWord(plainText.substring(currentIndex, currentLastIndex)));
result.push(plainText.substring(currentLastIndex));
// 結合して返す
return result.join('');
}
complexEmphasize("jk|cdef|abcd|fg|ghij|klmnop|pqr|ghi|rs|st|tuv|vw|wx|xyz", "abcdefghijklmnopqrstuvwxyz", "gi");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment