我正在尝试从“[something](link)”创建带标签的超链接。
我怎样才能将字符串转换成这样:something , 它在论坛中的完成方式?
这是我尝试过的,但我不太了解正则表达式:
$(function() {
var editor = $('.editor');
$('.output').html(
// editor.html().replace(/\[(.*)\)/g, '<a href="'+$1.replace(/\((.*)\)/g)+'">$1</a>')
editor.html().replace(/\[(.*)\)/g, '<a href="">$1</a>')
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contenteditable class="editor">
[something](link)
</div>
<div class="output">
</div>
最佳答案
您可以使用 /\[(.+)\]\((.+)\)/g
然后使用 $1
获取链接的文本和 $2
获取链接的 href
属性:
$n
wheren
is the capturing group position in the regular expression (a number) : the first capturing group is$1
, the second is$2
and so on.
$(() => {
const editor = $('.editor');
$('.output').html(editor.html().replace(/\[([^\[]+)\]\((.+)\)/g, '<a href="$2">$1</a>'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contenteditable class="editor">
[a link](https://example.com)
</div>
<div class="output"></div>
关于javascript - 正则表达式制作带标签的超链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57599818/