gpt4 book ai didi

javascript - 粘贴时如何将url自动转换为超链接

转载 作者:搜寻专家 更新时间:2023-10-31 22:20:38 24 4
gpt4 key购买 nike

当我尝试将 url 粘贴到 https://stackoverflow.com/ 之类的文本框中时,它不会自动转换为超链接。

我尝试使用正则表达式这是 Question我之前问过。我在这个问题中使用的函数工作正常,但实际上它会替换所有链接,包括标签中的链接(IMG,现有的 A HREF)。

我不想使用 regx 如果我使用 regx 转换发生在我单击任何提交或保存按钮时。

**当用户在文本框中粘贴 url 时,它应该会自动将任何链接转换为超链接****

我已经用 regx 试过了

例如:

what = "<span>In the task system, is there a way to automatically have any site / page URL or image URL be hyperlinked in a new window?</span><br><br><span>So If I type or copy http://www.stackoverflow.com/&nbsp; for example anywhere in the description, in any of the internal messages or messages to clients, it automatically is a hyperlink in a new window.</span><br><a href="http://www.stackoverflow.com/">http://www.stackoverflow.com/</a><br>    <br><span>Or if I input an image URL anywhere in support description, internal messages or messages to cleints, it automatically is a hyperlink in a new window:</span><br> <span>https://static.doubleclick.net/viewad/4327673/1-728x90.jpg</span><br><br><a href="https://static.doubleclick.net/viewad/4327673/1-728x90.jpg">https://static.doubleclick.net/viewad/4327673/1-728x90.jpg</a><br><br><br><span>This would save us a lot time in task building, reviewing and creating messages.</span>



Test URL's
http://www.stackoverflow.com/
https://stackoverflow.com/
https://stackoverflow.com/
www.stackoverflow.com
//stackoverflow.com/
<a href='https://stackoverflow.com/'>https://stackoverflow.com/</a>";

我试过这段代码

function Linkify(what) {
str = what; out = ""; url = ""; i = 0;
do {
url = str.match(/((https?:\/\/)?([a-z\-]+\.)*[\-\w]+(\.[a-z]{2,4})+(\/[\w\_\-\?\=\&\.]*)*(?![a-z]))/i);
if(url!=null) {
// get href value
href = url[0];
if(href.substr(0,7)!="http://") href = "http://"+href;

// where the match occured
where = str.indexOf(url[0]);

// add it to the output
out += str.substr(0,where);

// link it
out += '<a href="'+href+'" target="_blank">'+url[0]+'</a>';

// prepare str for next round
str = str.substr((where+url[0].length));
} else {
out += str;
str = "";
}
} while(str.length>0);
return out;
}

fiddle那是行不通的

当我们在文本框中粘贴 url 时是否可以自动转换它,就像我们进入堆栈流一样,我可以举一些例子吗?

谢谢。

最佳答案

这会起作用:

var newStr = str.replace(/(<a href=")?((https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)))(">(.*)<\/a>)?/gi, function () {
return '<a href="' + arguments[2] + '">' + (arguments[7] || arguments[2]) + '</a>'
});

JSFiddle hereRegexr

关于javascript - 粘贴时如何将url自动转换为超链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24162684/

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