Skip to content

Add target blank to external links #165

@albertcito

Description

@albertcito

Currently, the code removes all target blank by default. Can we add this code as an optional, in order to open the external links in a new window

This code will convert:

You are in [GitHub](https://github.com/)
to this
You are in [GitHub](https://github.com/){target=blank}

Also, we can convert all absolute URL without any format in blank. This code will convert:

You are in https://github.com/
to this
You are in [https://github.com/](https://github.com/){target=blank}

function absoluteURLtoTargetBlank(text) {
  // Regular expression to match absolute URLs
  // that are enclosed in brackets
  const pattern = /\[([^\]]*)\]\((https?:\/\/[^)]+)\)/g;
  const newContent = text.replace(pattern, '[$1]($2){target=blank}');

   // Regular expression to match absolute URLs
   // not enclosed in brackets or markdown links
   const absoluteUrlPattern = /(^|\s)(https?:\/\/[^\s\]\)]+)(?!\]\()(\s|$)/g;
   return newContent.replace(absoluteUrlPattern, '$1[$2]($2){target=blank}$3');
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions