如何使用 JavaScript 回调函数检测文本区域中的 url?

发布于 2024-11-25 21:31:43 字数 116 浏览 0 评论 0原文

如何使用 JavaScript 检测文本区域中的 url?使用 Facebook,您可以添加一个网址,一旦您完成粘贴/输入,它就会检测该地址。这怎么能做到呢?我对回调函数等做了很多研究,但想知道如何检测实际的 url?

How can you detect a url in a textarea with JavaScript? With Facebook you can add a url and it will detect the address as soon as you finished pasting/typing it. How can this be done? I've done a lot of research on callback functions, etc. but am wondering how I can detect an actual url?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

攀登最高峰 2024-12-02 21:31:43

如果您使用 jQuery,最简单的方法是使用 $.change()。

假设您有一个表单字段:

<input id="myField" type="text"/>

现在您可以将更改事件绑定到它,同时查明它是否是有效的 url:

$('#myField').keyup(function() {
    if(isUrl($(this).val()){
       //Show the url in an alert box
       alert($(this).val());
    }else{
       //do something if its not a url
    }
});

然后您将拥有一个检查 url 并返回布尔值的函数。请注意,我从此处获取此内容

function isUrl(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(s);
}

免责声明:我尚未测试任何 JavaScript,但这应该能让您很好地了解如何实现这一目标。

If you are using jQuery the easiest way is with $.change().

Say you have a form field:

<input id="myField" type="text"/>

Now you can tie a change event to it, and at the same time find out if its a valid url:

$('#myField').keyup(function() {
    if(isUrl($(this).val()){
       //Show the url in an alert box
       alert($(this).val());
    }else{
       //do something if its not a url
    }
});

Then you would have a function that checks for a url and returns a boolean value. Note, I took this from here

function isUrl(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(s);
}

Disclaimer: I haven't tested any of the javascript, but this should give you a good idea of how you could accomplish this.

dawn曙光 2024-12-02 21:31:43

只需处理 onkeyup 或类似事件,然后搜索与正则表达式匹配的文本区域的值。没有特殊的回调来捕获诸如“用户在文本区域中编写了链接”之类的事件:-) 因此您必须捕获现有事件并自行处理。

Just handle onkeyup or similar event and then search the value of the textarea matching the regular expression. There's no special callback to catch event like "user wrote a link in a textarea" :-) So you have to catch existing events and handle it yourself.

情深缘浅 2024-12-02 21:31:43

上一个答案中的正则表达式并不匹配所有可能的 URL,因为仅当它们以 ftp、http 或 https 开头时才会被检测到,因此 example.comwww.example.com 不会被发现。

此外,每次按下按键时都会进行验证,因此如果您编写像 example.com 这样的 url,它会先检测 example.co,然后检测 example。 com 如果您使用它来获取额外信息(例如获取找到的 URL 的 META),这可能会很糟糕。

setTimeout()clearTimeout() 有助于减少验证频率

请参阅:
当用户完成输入而不是按键时运行javascript函数?


这里是我最终得到的代码:

var typingTimer;
var doneTypingInterval = 1000;

$(function() {
  // Check textarea on load
  checkTextareaUrl();

  // Check textarea on key pressed
  $('textarea').keyup(function() {
    clearTimeout(typingTimer);
    typingTimer = setTimeout(checkTextareaUrl, doneTypingInterval);
  });
});

function checkTextareaUrl()
{
  var url = checkUrl($('textarea').val());

  if (url)
  {
    // Action when an url is found
    $('.url').text('Url found: '+ url);
  }
  else
  {
    // Action when an url is found
    $('.url').text('No url found');
  }
}

function checkUrl(string)
{
  var regex = /(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,63}(:[0-9]{1,5})?(\/.*)?/;
  return regex.test(string) ? string.match(regex)[0] : false;
}
textarea {
  width: 500px;
  height: 100px;
}

.url { font-weight: 700; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea>Lorem ipsum dolor sit amet, example.com consectetur adipiscing elit. Mauris at massa quis www.example.com metus sagittis sollicitudin. Donec posuere, enim quis tincidunt varius,  http://example.com nibh lorem vulputate massa, sed cursus lacus justo at ante. http://www.example.com</textarea>

<div class="url"></div>


如果您需要获取所有 URL,您可以使用此函数,它返回包含所有可用 URL 的数组:

function checkUrls(string)
{
  var regex = /(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,63}(:[0-9]{1,5})?(\/.*)?/g;
  return regex.test(string) ? string.match(regex) : false;
}

The regex on previous answer doesn't match all possible URL because they are detected only if they begin with ftp, http or https, so example.com or www.example.com would not be found.

Also, the verification is made everytime you press a key so if you're writing an url like example.com, it will detect example.co then example.com which could be bad if you use it for extra information (like getting META of found URL).

setTimeout() and clearTimeout() help to reduce the frequency of verification

See :
Run javascript function when user finishes typing instead of on key up?


Here the code I end up with :

var typingTimer;
var doneTypingInterval = 1000;

$(function() {
  // Check textarea on load
  checkTextareaUrl();

  // Check textarea on key pressed
  $('textarea').keyup(function() {
    clearTimeout(typingTimer);
    typingTimer = setTimeout(checkTextareaUrl, doneTypingInterval);
  });
});

function checkTextareaUrl()
{
  var url = checkUrl($('textarea').val());

  if (url)
  {
    // Action when an url is found
    $('.url').text('Url found: '+ url);
  }
  else
  {
    // Action when an url is found
    $('.url').text('No url found');
  }
}

function checkUrl(string)
{
  var regex = /(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,63}(:[0-9]{1,5})?(\/.*)?/;
  return regex.test(string) ? string.match(regex)[0] : false;
}
textarea {
  width: 500px;
  height: 100px;
}

.url { font-weight: 700; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea>Lorem ipsum dolor sit amet, example.com consectetur adipiscing elit. Mauris at massa quis www.example.com metus sagittis sollicitudin. Donec posuere, enim quis tincidunt varius,  http://example.com nibh lorem vulputate massa, sed cursus lacus justo at ante. http://www.example.com</textarea>

<div class="url"></div>


If you need to get all URLs, you can use this function which return an array with all available URLs :

function checkUrls(string)
{
  var regex = /(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,63}(:[0-9]{1,5})?(\/.*)?/g;
  return regex.test(string) ? string.match(regex) : false;
}
流殇 2024-12-02 21:31:43
<textarea id="Testing" onkeypress="detectUrlExists" onblur="detectUrl" />


function detectUrlExists (event) {
    let urlIndex = event.target.value.match(/https:\/\//)?.index
    if (urlIndex) {
        //add lines to proceed after detecting url exists
    }
}

function detectUrl () {
    let val = document.getElementById('Testing').value
    let urls = val.split(' ').filter(el => el.startsWith('https://'))
}
<textarea id="Testing" onkeypress="detectUrlExists" onblur="detectUrl" />


function detectUrlExists (event) {
    let urlIndex = event.target.value.match(/https:\/\//)?.index
    if (urlIndex) {
        //add lines to proceed after detecting url exists
    }
}

function detectUrl () {
    let val = document.getElementById('Testing').value
    let urls = val.split(' ').filter(el => el.startsWith('https://'))
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文