有人对检测字符串中的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。


当前回答

这里有一个不使用任何库的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;



其他回答

首先,你需要一个匹配url的正则表达式。这很难做到。看这里,这里和这里:

...almost anything is a valid URL. There are some punctuation rules for splitting it up. Absent any punctuation, you still have a valid URL. Check the RFC carefully and see if you can construct an "invalid" URL. The rules are very flexible. For example ::::: is a valid URL. The path is ":::::". A pretty stupid filename, but a valid filename. Also, ///// is a valid URL. The netloc ("hostname") is "". The path is "///". Again, stupid. Also valid. This URL normalizes to "///" which is the equivalent. Something like "bad://///worse/////" is perfectly valid. Dumb but valid.

无论如何,这个答案并不是为了给您最好的正则表达式,而是为了证明如何使用JavaScript在文本中进行字符串包装。

所以让我们用这一个:/ (https ?: \ / \ / ^ \ [s] +) / g

同样,这是一个糟糕的正则表达式。它会有很多假阳性。但是对于这个例子来说已经足够好了。

函数urlify(text) { var urlRegex = /(https?:\/\/[^\s]+)/g; 返回文本。替换(urlRegex,函数(url) { 返回'<a href="' + url + '">' + url + '</a>'; }) //或者 //返回文本。替换(urlRegex, '<a href="$1">$1</a>') } var text = '在http://www.example.com和http://stackoverflow.com上找到我'; Var HTML = urlify(文本); console.log (html)

// html now looks like:
// "Find me at <a href="http://www.example.com">http://www.example.com</a> and also at <a href="http://stackoverflow.com">http://stackoverflow.com</a>"

所以总的来说:

$$('#pad dl dd').each(function(element) {
    element.innerHTML = urlify(element.innerHTML);
});

根据新月新鲜的答案

如果你想检测链接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>';
    }) 
}

有一个现有的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>';
  });

您可以使用这样的正则表达式来提取正常的url模式。

(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})

如果需要更复杂的模式,可以使用这样的库。

https://www.npmjs.com/package/pattern-dreamer

下面是我最终使用的正则表达式:

var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

这不包括URL中的尾随标点符号。新月的功能就像一个魅力:) 所以:

function linkify(text) {
    var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(urlRegex, function(url) {
        return '<a href="' + url + '">' + url + '</a>';
    });
}