有人对检测字符串中的url有什么建议吗?

arrayOfStrings.forEach(function(string){
  // detect URLs in strings and do something swell,
  // like creating elements with links.
});

更新:我最终使用这个正则表达式进行链接检测……显然是在几年后。

kLINK_DETECTION_REGEX = /(([a-z]+:\/\/)?(([a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|local|internal))(:[0-9]{1,5})?(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-zA-Z0-9!$&'()*+.=-_~:@/?]*)?)(\s+|$)/gi

完整的帮助器(带有可选的句柄支持)位于gist #1654670。


当前回答

检测文本中的url并使其可点击。

const detectURLInText = (contentElement) => { const elem = document.querySelector(contentElement); 初步的。innerHTML = elem.innerHTML.replace (/ (https ?: \ \ / ^ \ [s] +) / g,”<类=链接的href = " $ 1 " > < / > ' 1美元) 返回elem } detectURLInText(“# myContent”); < div id = " myContent " > 地狱的世界!,检测文本中的url并使其可点击。 IP地址:https://123.0.1.890:8080 网站:https://any-domain.com < / div >

其他回答

tmp。innerText未定义。您应该使用tmp.innerHTML

function strip(html) 
    {  
        var tmp = document.createElement("DIV"); 
        tmp.innerHTML = html; 
        var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;   
        return tmp.innerHTML .replace(urlRegex, function(url) {     
        return '\n' + url 
    })

这里有一个不使用任何库的react应用程序的小解决方案,请注意,如果url没有附加到任何字符,这个方法是有效的

该组件将返回一个带有扭结检测的段落!

import React from "react";


interface Props {
    paragraph: string,
}

const REGEX = /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/gm;

const Paragraph: React.FC<Props> = ({ paragraph }) => {
  
    const paragraphArray = paragraph.split(' ');
    return <div>

        {
            paragraphArray.map((word: any) => {
                return word.match(REGEX) ? (
                    <>
                        <a href={word} className="text-blue-400">{word}</a> {' '}
                    </>
                ) : word + ' '
            })
        }
    </div>;
};

export default LinkParaGraph;



有一个现有的npm包:url-regex,只需用yarn添加url-regex或npm安装url-regex,然后像下面这样使用:

const urlRegex = require('url-regex');

const replaced = 'Find me at http://www.example.com and also at http://stackoverflow.com or at google.com'
  .replace(urlRegex({strict: false}), function(url) {
     return '<a href="' + url + '">' + url + '</a>';
  });
let str = 'https://example.com is a great site'
str.replace(/(https?:\/\/[^\s]+)/g,"<a href='$1' target='_blank' >$1</a>")

短代码大工程!

结果:-

 <a href="https://example.com" target="_blank" > https://example.com </a>

根据新月新鲜的答案

如果你想检测链接http://或没有http://和通过www。你可以使用下面的方法

function urlify(text) {
    var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
    //var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url,b,c) {
        var url2 = (c == 'www.') ?  'http://' +url : url;
        return '<a href="' +url2+ '" target="_blank">' + url + '</a>';
    }) 
}