gpt4 book ai didi

Javascript编写正则表达式将http替换为html标签

转载 作者:行者123 更新时间:2023-11-28 04:50:46 24 4
gpt4 key购买 nike

如何使该字符串成为文本

first video link: https://www.youtube.com/watch?v=123456

second video link: https://www.youtube.com/watch?v=8123123`;

成为

first video link: 
<a href="https://www.youtube.com/watch?v=123456">
https://www.youtube.com/watch?v=123456
</a>

second video link:
<a href="https://www.youtube.com/watch?v=8123123">
https://www.youtube.com/watch?v=8123123
</a>

我编写了一个正则表达式来解析链接

这是我所拥有的。

<script type="text/javascript">
var myString =`first video link: https://www.youtube.com/watch?v=123456
second video link: https://www.youtube.com/watch?v=8123123`;
var myRegexp = /(https|http)?:\/\/[\S]+/g;
var match = myRegexp.exec(myString);
console.log(match[0]) // https://www.youtube.com/watch?v=123456
</script>

最佳答案

使用以下解决方案:

var myString = "first video link: https://www.youtube.com/watch?v=123456\nsecond video link: https://www.youtube.com/watch?v=8123123"; 
var myRegexp = /https?:\/\/\S+/g;
var match = myString.replace(myRegexp, '<a href="$&"><br> $&<br></a>');
document.body.innerHTML = match;

https?:\/\/\S+ 将匹配 http,然后是可选的 s,然后是 ://,然后 \S+ 将匹配一个或多个非空白符号。整个匹配值可以通过 $& 反向引用插入到 String#replace() 替换模式中的结果字符串中。

关于Javascript编写正则表达式将http替换为html标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42945714/

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