2011-12-16 9 views
8

テキスト領域のテキストからの画像リンクのうち、通常のリンクやタグからタグを作成する関数を記述しようとしています。URLをhtmlに変換する<a>タグと画像URLを<img>とjavascriptの正規表現

これは両方で初めて動作しますが、そこに「a href」タグを貼り付けると2重にリンクします。 imageRegexチェックのためにイメージは作成されません。どのようにこれを動作させるためにどのようなアイデアですか?

テキストエリアには両方のタイプの複数のURLがあることに注意してください。

$("#message").blur(function() { 
    var imageRegex = /\.(png|jpg|jpeg|gif)$/; 
    var s = $(this).val().replace(/(?:^|[^"'])(\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|])/gim, function(str) { 
     if (str.match(imageRegex)) { 
      return('<img src="' + str + '" />'); 
     } else { 
      return('<a href="' + str + '">' + str + '</a>'); 
     }  
    }); 
    $(this).val(s);   
}); 
+2

+1 - これは学習の練習ですか、仕事ですか?後者の場合は、jQueryを推奨します。 –

+0

これは私が運営する音楽メッセージボードです。私はjqueryに私は正規表現を動作させることができますが、正規表現自体はとにかく変更されませんこの機能を切り替えるでしょう。 –

+0

私はそれを理解しました。サイトが私に許可するときに回答を投稿します。他の人には –

答えて

2

私はjQueryですばらしいとは言えませんが、私はあなたの問題にバニラのソリューションを作りました。このフィドルをチェックしてください! http://jsfiddle.net/dv0s5onj/

var yourString=document.getElementById('message').innerHTML; 

var count=0; 

var urls=yourString.match(/(?:^|[^"'])(\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|])/gim); 
// Make an array of urls 

urls.forEach(function(v,i,a){ 
    var n = yourString.indexOf(v,count); //get location of string 

    if(v.match(/\.(png|jpg|jpeg|gif)$/)===null){// Check if image 
     // If link replace yourString with new anchor tag 
     yourString = strSplice(yourString,n,v.length,'<a href="'+v+'">'+v+'</a>'); 
     count += (v.length*2)+16;// Increase count incase there are multiple of the same url. 
    }else{ 
     // If link replace yourString with img tag 
     yourString = strSplice(yourString,n,v.length,'<img src="'+v+'" height="120px;" width="120px;"/>'); 
     count += v.length+14;// Increase count incase there are multiple of the same url. 
    } 
}); 

// A function to splice strings that I found on another StackOverflow Question. 
function strSplice(str, index, count, add) { 
    return str.slice(0, index) + (add || "") + str.slice(index + count); 
} 

//Replace the value of your element with your string 
document.getElementById('message').innerHTML=yourString;