javascript - 如何确定用户输入的哪些部分应该像 Stack Overflow 那样转换为链接?

标签 javascript string url hyperlink

Stackoverflow.com 以某种方式将某些文本检测为链接并将其转换,例如:

https://en.wikipedia.org/wiki/Möbius_strip or<br>
https://zh.wikipedia.org/wiki/Wikipedia:关于中文维基百科/en
https://en.wikipedia.org/wiki/Saw_(disambiguation)

https://stackoverflow.com/questions/43987894/as-of-may-15-2017-what-characters-are-arent-allowed-in-a-web-address-as-typed

向您显示,亲爱的读者,如下:

https://en.wikipedia.org/wiki/Möbius_strip
https://zh.wikipedia.org/wiki/Wikipedia:关于中文维基百科/en https://en.wikipedia.org/wiki/Saw_(disambiguation)

As of May 15, 2017, what characters are/aren't allowed in a web address as typed/pasted by a user (preferably in regex form)?

有人会如何实现类似的系统(如果该网站使用的特定算法是专有的,则尊重知识产权)?

我正在寻找可以处理上述所有情况的东西。如果它超越并正确处理 https://❤❤❤.ws/,但不幸的是,这个网站没有做到这一点,则会获得奖励积分。

另请注意: http://<IFRAME SRC="javascript:alert('XSS');"></IFRAME> 变成了 http://因此避免不安全的 html 很重要。

最佳答案

使用正则表达式来匹配以 https:// 开头的字符串到第一个空格并替换为替换模式。

var str = "http://❤❤❤.ws/";
var link = str.replace(/(http(|s):\/\/[^<\s]*)/, '<a href="$1">$1</a>');
document.write(link);

获取标题。 Access-Control-Allow-Origin 策略适用。

fetch(link.match(/http:[^ ]+/))

.then(response => {
    return response.text()
})

.then(body => {
    document.write(body.match(/<title>([^<]*)<\/title>/)[1]);
});

Fetch API

关于javascript - 如何确定用户输入的哪些部分应该像 Stack Overflow 那样转换为链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44012499/

相关文章:

javascript - 在 angularjs 中转换 $.param

javascript - 我怎样才能解构这个数组?

string - 获取 UITextView 中的当前段落?

java - Str.lastIndexOf ("\")给出错误

.net - Process.Start(url),url 中带有 anchor

ruby - URI 响应代码

javascript - 在做某事之前如何确认所有复选框都已选中?

javascript - 如果源设置为透明像素,则图像标签背景图像不显示

c++ - 理解 C++ 字符串

ajax - 我应该使用 hashbang/shebang 吗?