Javascript find link in text

Today we will show you how to detect URLs in text and create a link in JavaScript. When you are working with a messaging application where you may need to detect the URL from the chat message string and create a clickable HTML link instead of that text. So I am going to share the JavaScript function with you.

Читайте также:  Наименование методов в java

Checkout more articles on JavaScript

Split this example in two different parts

1. Detect URLs from the string

Here, we’ll use the match method of the string along with the regular expression to detect the URLs in text. This method will provide us the list of the URLs in the array.

function detectURLs(message) < var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g; return message.match(urlRegex) >detectURLs("Visit www.codepremix.com and contact us on https://www.codepremix.com/contact to share your queries.") // Output: ["www.codepremix.com", "https://www.codepremix.com/contact"]

In the next step, we will create a clickable link instead of the URLs. Here, we will use the replace method of the string and that method will be used to create a HTML `a` tag in the text.

function replaceURLs(message) < if(!message) return; var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g; return message.replace(urlRegex, function (url) < var hyperlink = url; if (!hyperlink.match('^https?:\/\/')) < hyperlink = 'http://' + hyperlink; >return '' + url + '' >); > replaceURLs("Visit www.codepremix.com and contact us on https://www.codepremix.com/contact to share your queries.") // Output: Visit www.codepremix.com and contact us on https://www.codepremix.com/contact to share your queries.

I hope you find this article helpful.
Thank you for reading. Happy Coding.

You Might Also Like

How to get first N elements of an array in JavaScript

How to get first N elements of an array in JavaScript

Grouping array of object based on first letter in JavaScript

April 7, 2022

Grouping array of object based on first letter in JavaScript

How to convert seconds to minutes and hours in JavaScript

August 16, 2021

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

JavaScript plugin for finding links in plain-text and converting them to HTML tags.

License

Hypercontext/linkifyjs

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Linkify is a JavaScript plugin. Use Linkify to find links in plain-text and convert them to HTML tags. It automatically highlights URLs, #hashtags, @mentions and more.

  • Detect URLs and email addresses
  • #hashtag, @mention and #-ticket plugins
  • React and jQuery support
  • Multi-language and emoji support
  • Custom link plugins
  • Fast, accurate and small footprint (~20kB minified, ~11kB gzipped)
  • 99% test coverage
  • Compatible with all modern browsers (Internet Explorer 11 and up)

Download the latest release for direct use in the browser, or install via NPM:

npm install linkifyjs linkify-html 

When developing in an environment with JavaScript module loader such as Webpack, use an import statement:

import * as linkify from 'linkifyjs'; import linkifyHtml from 'linkify-html';

Or in Node.js with CommonJS modules

const linkify = require('linkifyjs'); const linkifyHtml = require('linkify-html');

Note: When linkify-ing text that does not contain HTML, install and use the linkify-string package instead of linkify-html . Read more about Linkify’s interfaces.

Example 1: Convert all links to tags in the given string

const options =  defaultProtocol: 'https' >; linkifyHtml('Any links to github.com here? If not, contact test@example.com', options);

Returns the following string:

'Any links to github.com here? If not, contact test@example.com'

To modify the resulting links with a target attribute, class name and more, use the available options.

Example 2: Find all links in the given string

linkify.find('Any links to github.com here? If not, contact test@example.com');

Returns the following array

[  type: 'url', value: 'github.com', isLink: true, href: 'http://github.com', start: 13, end: 23 >,  type: 'email', value: 'test@example.com', isLink: true, href: 'mailto:test@example.com', start: 46, end: 62 > ]

Example 3: Check whether a string is a valid link:

Check if as string is a valid URL or email address:

linkify.test('github.com'); // true

Check if a string is a valid email address:

linkify.test('github.com', 'email'); // false linkify.test('noreply@github.com', 'email'); // true

Usage with React, jQuery or the browser DOM

Read the interface documentation to learn how to use linkify when working with a specific JavaScript environment such as React.

Plugins for @mentions, #hashtags and more

By default Linkify will only detect and highlight web URLs and e-mail addresses. Plugins for @mentions, #hashtags and more may be installed separately. Read the plugin documentation.

Linkify natively supports all modern browsers.

Linkify is tested on Node.js 10 and up. Older Node.js versions are unofficially supported.

View full documentation at linkify.js.org/docs

Источник

Today we will show you how to find URLs in string and make a link using JavaScript. Recently I was developing a messaging application where we need to detect the URL from the chat message string and create a clickable HTML link instead of that text. So I am going to share the JavaScript function with you.

Split this example in two different parts

1. Detect URLs from the string

Here, we’ll use the match method of the string along with the regular expression to detect the URLs in text. This method will provide us the list of the URLs in the array.

detectURLs ( «Visit www.cluemediator.com and subscribe us on https://www.cluemediator.com/subscribe for regular updates.» )

In the next step, we will create a clickable link instead of the URLs. Here, we will use the replace method of the string and that method will be used to create a HTML a tag in the text.

replaceURLs ( «Visit www.cluemediator.com and subscribe us on https://www.cluemediator.com/subscribe for regular updates.» )

That’s it for today.
Thank you for reading. Happy Coding.

You may also like.

Important HTTP Status Codes - Clue Mediator

Important HTTP Status Codes

How to remove HTML tags from a string using JavaScript - Clue Mediator

How to remove HTML tags from a string using JavaScript

How to Lazy Load Images in JavaScript - Clue Mediator

How to Lazy Load Images in JavaScript

How to prevent the submit form on enter key except the textarea using jQuery - Clue Mediator

How to prevent the submit form on enter key except the textarea using jQuery

International telephone input with country flags and dial codes using jQuery - Clue Mediator

International telephone input with country flags and dial codes using jQuery

How to convert PHP array to JavaScript array - Clue Mediator

How to convert PHP array to JavaScript array

2 Responses

Leave a Reply Cancel reply

Search your query

Recent Posts

  • Change a Password for MySQL on Linux using Command Line July 27, 2023
  • Executing MySQL Queries Directly From the Command Line July 26, 2023
  • Listing tables and their structure with the MySQL Command Line July 25, 2023
  • How to Import an .sql File into a Remote Server from a Local Machine July 24, 2023
  • How to Copy a File from/to a Remote Server using Command Line July 23, 2023

Tags

Join us

Top Posts

Explore the article

We are not simply proficient at writing blog post, we’re excellent at explaining the way of learning which response to developers.

For any inquiries, contact us at [email protected] .

  • We provide the best solution to your problem.
  • We give you an example of each article.
  • Provide an example source code for you to download.
  • We offer live demos where you can play with them.
  • Quick answers to your questions via email or comment.

Clue Mediator © 2023. All Rights Reserved.

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.

Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Tiny little tool to find URLs in a string of text and hyperlink them

License

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

autolink-js is a small (about half a kilobyte), simple, and tested JavaScript tool that takes a string of text, finds URLs within it, and hyperlinks them.

Why bother releasing such a tiny little method?

I recently needed to find and hyperlink URLs in user-submitted text and was surprised to find that doing what seemed like such a simple task wasn’t already a Solved Problem. Different regex solutions led to different unwanted side effects, and other utilities were far, far more complex and feature rich than I needed.

autolink-js adds an autoLink() method to JavaScript’s String prototype, so you can use it on any JavaScript string. Take a look at the tests, but essentially, after including either autolink.js or autolink-min.js to your page, it works like this:

You can pass any additional HTML attributes to the anchor tag with a JavaScript object, like this:

Callback option can be used to redefine how links will be rendered.

// Input "This is a link to image http://example.com/logo.png".autoLink( callback: function(url)  return /\.(gif|png|jpe?g)$/i.test(url) ? '+ url + '">' : null; > >); // Output "This is a link to image "

Open example/example.html in your web browser and view the source for a simple but full-featured example of using with jQuery.

After cloning this repository, simply open test/suite.html in your web browser. The tests will run automatically.

About

Tiny little tool to find URLs in a string of text and hyperlink them

Источник

Оцените статью