Javascript - 获取文本区域中的所有网址

标签 javascript jquery regex

我正在寻找一个干净的 jquery 代码,它在 textarea 中返回 url。我找到了一些解决方案,但不是很有用。 假设我有一些文字:

I have visited https://jobscane.com and it was so useful for finding jobs in pakistan. and https://google.com helped me to find it.

所以脚本应该在上面的字符串中返回 2 个 url

到目前为止我已经尝试过的是。

<script>
  $(document).ready(function(){

    $("#textarea").on('keyup', function(){

    const regex = /((?:https?:|www\.)[^\s]+)/g;
    const str = $(this).val();
    let m;

    while ((m = regex.exec(str)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }

        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
            console.log(`Found match, group ${groupIndex}: ${match}`);
        });
    }

     });

  });
</script>

最佳答案

可以摆脱 while 并使用 match()

$("textarea").on('keyup', function() {

  const regex = /((?:https?:|www\.)[^\s]+)/g;
  const str = $(this).val();

  let m = str.match(regex);

  if (m) {
    m.forEach((match, groupIndex) => {
      console.log(`Found match, group ${groupIndex}: ${match}`);
    });
  }


}).keyup(); // trigger event for demo
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea> I have visited https://jobscane.com and it was so useful for finding
jobs in pakistan. and https://google.com helped me to find it.

</textarea>

关于Javascript - 获取文本区域中的所有网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51458823/

相关文章:

javascript - 如何在类里面编写 Mocha 测试

javascript - 推特嵌入式时间线永不更新

javascript - 如何更改下面给出的 json 数组?

regex - MongoDB $regex 查询和潜在利用

javascript - 如何排序道场/多选列表

javascript - addEventListener 中的 Event 对象如果没有传入回调,从哪里来?

php - 如何从 php 变量在 jquery 中分配一个类?

jquery - Bootstrap 3 : Affix navbar fade in and add object

JavaScript 正则表达式 : validate time

python - 用于捕获和替换字符串中除特殊模式外的所有数字的 RegEx