Souleste
Souleste

Reputation: 1984

Regex make labeled hyperlink

I am trying to make a labeled hyperlink from "[something](link)".

How can I convert the string to something like this: something, the way it is done in forums?

Here is what I have tried, but I don't know regex very well:

$(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>

Upvotes: 1

Views: 83

Answers (2)

Bee
Bee

Reputation: 1306

Solution

This regex should do what you want.

/\[(.*?)\]\((.*?)\)/g

This regex also takes care about input strings like [something] [something](link).

\[([^\[]*?)\]\((.*?)\)

Explanation

This regex matches everything within square brackets into capture group 1 directly followed by a curved brackets pair which contents go into capture group 2. Capture groups are defined by a curved bracket pair. Afterwards those capture groups can be accessed by using $1 and $2.

The regex also covering the input string [something] [something](link) does not match everything within a bracket pair but instead matches everything except opening brackets.

Example

Here is the updated snippet which you posted.

$(function() {

  var 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">
  [something](link)
</div>
<div class="output">

</div>

Upvotes: 2

ThS
ThS

Reputation: 4783

You can use /\[(.+)\]\((.+)\)/g and then use $1 to get the link's text and $2 to get the link's href attribute :

$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>

Upvotes: 2

Related Questions