J
J
Jhon Do2020-04-23 02:37:45
JavaScript
Jhon Do, 2020-04-23 02:37:45

How to recognize a link in a string?

We are talking about the behavior of the search bar on the site, similar to what the address bar of the browser does. If it is a link, then it follows it, if it is just text, then it searches in the selected search engine. How to implement this on the site page? It only comes to mind to cycle through the string character by character, and if a domain ending is found, follow the link. But for the site is not "hard"? What other ways are there?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Arseny, 2020-04-23
@Spellman30

Yep, I sort of get it.
The link has some attributes based on which you can recognize it. Among them:
1. Protocol: http\s (there is an example in the answers)
2. Domain + domain zone (here it’s more difficult, since domain zones are overdominal )
I don’t recommend checking by domain zone and by the principles of name.zone. Because of this approach, I still keep a couple of boxes with a class-correct zone in order to be able to enter services that did not bother to do a norm check.
The search string, by the way, is also not ideal, because it works on a similar principle and you can easily fly away to some dot.com . However, no one forbids you to make a bad interface, "because everyone does it."
Sobsno, you need to build a regular expression that will check the string entered by the user during input or on an event, say, submitting a form, it already depends on how you implemented it, according to the condition that suits you. You can implement this from the reverse principle, by collecting examples of links that you want to catch and compiling a regular expression for them. This service will help you with this .

D
Dmitry Belyaev, 2020-04-23
@bingo347

The only 100% working way to check if a link is in a string is to try parsing it as a link:

function isURL(str) {
  try {
    new URL(str);
    return true;
  } catch {
    return false;
  }
}

console.log(isURL('http://')); // false
console.log(isURL('http://site.ru')); // true

And do not listen to those who offer you regulars. Regular games are very expensive both in terms of computing resources and code support. People use regular expressions only in 2 cases:
1. they don’t have time to do it right, but then they intend to redo it
2. they are macaques not able to do it right

X
xmoonlight, 2020-04-23
@xmoonlight

The simplest is:
1. Check the number (examples: 1234, 755676555) for id-shnik
2. Check the "glued" word with at least one slash (examples: "text/text", "user/profile") for a link
. ..for an entry in sitemap.xml after both strings being compared (the one being checked and the one contained in the file) are converted to lower case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question