-1
私はa
タグを使って文字列のリンクをラップ/解析するために以下の関数を使用します。 これは文字列内のプレーンリンクだけでなく、[title](link)
のようなマークダウン表記もサポートしています。ハイパーリンクの前に `// 'を追加する正規表現
しかし、私は問題があります://
がない場合、href属性に//
をどのように記入するのですか?
テストデータ:
google.com // ok: leave this as is
www.google.com // error: need to add `//` in href value
http://google.com // ok
http://www.google.com // ok
[google](google.com) // error: need to add `//` in href value
[google](www.google.com) // error: need to add `//` in href value
[google](http://google.com) // error: need to add `//` in href value
はあなたがコールバック関数でreplace
メソッドを使用することができJS fiddle
var markdownParse = (function() {
return {
autoLinks: function(text, options) {
var simpleURLRegex = /\b(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+)(?=\s|$)(?!["<>])/gi;
text = text.replace(simpleURLRegex, '<a href=\"$1\">$1</a>');
return text;
},
stripLinkDefinitions: function(text) {
text = text.replace(/\[(.*?)\]\((.*?)\)/gi, '<a href="$2">$1</a>');
return text;
},
}
})();
$('.convert').on('click', function() {
\t var inputVal = $('.input').val();
inputVal = markdownParse.autoLinks(inputVal);
inputVal = markdownParse.stripLinkDefinitions(inputVal);
$('.output').html(inputVal)
});
.convert {
cursor: pointer;
}
.output {
white-space: pre;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea class="input"></textarea>
<div class="output"></div>
<div class="convert">convert</div>
この正規表現は2つの関数を混合しますか?どのように2つの機能に戻って分ける? – user1775888
なぜあなたはそれをしたいですか? – trincot
私はこのライブラリを呼び出すことができるので、オプションは '[]()'スタイルマークダウンまたはインラインリンクを使用するように選択します – user1775888