2014年3月11日火曜日

特定の文字に色を付ける

ドキュメントから test を探し<span></span>で囲んでcssを付けてます。
function setWordHighlight (word) {
  var doc = document,
      df = doc.createDocumentFragment(),
      span = doc.createElement('span'),
      texts = doc.evaluate('descendant::text()[normalize-space(.)]', doc.body, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 
  span.className = 'high-light';
  span.appendChild(doc.createTextNode(word));
 
  for (var i = 0, l = texts.snapshotLength, stringsLength, textNode; i < l; ++i) {
    textNode = texts.snapshotItem(i);
    strings = textNode.data.split(word);
    stringsLength = strings.length;

    if (stringsLength > 1) {
      df.appendChild(doc.createTextNode(strings[0]));

      for (var j = 1; j < stringsLength; ++j) {
        df.appendChild(span.cloneNode(true));
        df.appendChild(doc.createTextNode(strings[j]));
      }
     
      textNode.parentNode.replaceChild(df, textNode);
    }
  }
}

setWordHighlight('test');

css:
.high-light { color: black; background-color: yellow; font-weight: bold; }

http://jsfiddle.net/3F4Wa/
http://toro.2ch.net/test/read.cgi/hp/1386098775/898


2013年11月6日水曜日

ループの高速化

全要素を走査し順番に意味が無い場合、若干ですが高速化できます。
 
for (var i = 0; i < list.length; i++) {
   console.log(list[i]); 
}

毎回、.lengthを参照するのは無駄ですので予め変数に入れておきます。

for (var i = 0, len = list.length; i < len; i++) {
    console.log(list[i]); 
}

順番に意味がないのなら、最後から走査することでさらに簡略化できます。
 
var i = list.length - 1;
for (; i >= 0; i--) {
   console.log(list[i]); 
}


2013年10月14日月曜日

配列かどうかを見分けるにはarray instanceof Arrayでは不十分

array instanceof Array
では不十分なので
Array.isArray(obj)
を使用する 
 
古いブラウザでは↓を追加しとく
 
if (!Array.isArray) {  
  Array.isArray = function (vArg) {  
    return Object.prototype.toString.call(vArg) === "[object Array]";  
  };  
}
 

2013年9月21日土曜日

末尾の文字を取り除く方法

文字列末尾に / があった時に取り除く方法

s = s.replace(/\/$/,'');

// ↑より高速
if ('/' === s.charAt(s.length - 1))
  s.slice(0, -1);


// ES6から
if (s.endsWith('/'))
  s.slice(0, -1);

2013年9月11日水曜日

リファラを消す

a.onclick = function () {

     //remove referer

    this.href = "data:text/html;charset=utf-8," + encodeURIComponent('<script>\x3c!--\ndocument.write(\'<meta http-equiv="refresh" content="0;url=' + this.href + "\">');//--\x3e\x3c/script>")

}