文章

Short-Amazon (regular expression 版)

某天看到 Othree 寫了個 short-amazon 來縮短 Amazon 網址,我依樣葫蘆地試用 regular expression 的方式做一次:


 function convert(){ 
  var output = parseUrl(document.getElementById("input").value); 
  document.getElementById('output').value = output; 
 }
 var parseUrl = function(input){ 
  if(!input) return ''; 
  var lines = input.split('n'); 
  var re = /^(http://www.amazon.[w.]{2,6}).*(/(dp|gp/product)/[A-z0-9]*)(/|?).*/; 
  var result = ''; 
  for(var i in lines){ 
    var l = lines[i]; 
    if(re.test(l)){ 
      l = l.replace(re,'$1$2'); 
    } 
    result += l + 'n'; 
  } 
  return result; 
 }
 document.getElementById('output').onfocus = function () {this.select();}; 
 document.getElementById('input').onkeyup =  
 document.getElementById('input').onblur =  
 document.getElementById('input').onchange = convert;

當然,用 regular expression 的缺點就是沒有那麼好讀。

這原本是寫在 JS Bin (很方便!),但因為 JS Bin 會定期做 house keeping,所以特此記下。

*