javascript - 正则表达式制作带标签的超链接

标签 javascript jquery regex

我正在尝试从“[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 where n 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/

相关文章:

javascript - 使用 AngularJS 加载动态指令 - 错误 : Access to restricted URI denied

javascript - jQuery 计算空格

1 个大写 1 个特殊字符和 1 个小写的正则表达式

regex - 在vim中,如何复制正则表达式模式?

javascript - 在html中更改占位符字体颜色

java - 什么是文件 ://protocol url encodings for these special characters(; $ % ^ #)

Javascript 在函数调用中跳过参数

javascript - 使用 Firebase 中两个位置的数据,同时读取数据

javascript - 如何根据所选选项Javascript更改html中的值

javascript - 如何显示 future 复选框元素的值?