gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:21:17 26 4
gpt4 key购买 nike

我正在寻找一个干净的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com