0

次のテキストを解析して、アンカー タグを含む書式設定された URL に変換したいと考えています。

something is wrong with http://www.gbin1.com/index.html,  but cannot find the reason in http://www.google.com

<a href="url">url</a>以下に示すように、上記のテキスト URL を JavaScript を使用して置き換え、短縮するにはどうすればよいですか。

something is wrong with <a href="http://www.gbin1.com/index.html">gbin1.com</a>,  but cannot find the reason in <a href="http://www.gbin1.com">google.com</a>
4

1 に答える 1

2

この解決策を確認してください。

var x = "something is wrong with http://www.gbin1.com/index.html,  but cannot find the reason in http://www.google.com";
var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var split = x.split(" ");
for(var i=0; i< split.length; i++){
    if(split[i].match(regex)){
        var text = split[i].split(".").slice(1).join(".").split("/")[0];

        split[i] = '<a href=\"' +split[i]+'\">'+text+'</a>';
    }
}
console.log(split.join(" "));

http://jsfiddle.net/4JGY7/

于 2012-07-02T16:38:12.197 に答える