Javascript 将字符串拆分为文本/http链接

Javascript 将字符串拆分为文本/http链接,javascript,regex,Javascript,Regex,我试图获取一个文本字符串并从中创建一个数组,以便字符串: var someText='I am some text and check this out! http://blah.tld/foo/bar Oh yeah! look at this too: http://foobar.baz'; 在此处插入神奇的正则表达式,然后 该阵列将如下所示: theArray[0]='I am some text and check this out! ' theArray[1]='http://

我试图获取一个文本字符串并从中创建一个数组,以便字符串:

var someText='I am some text and check this out!  http://blah.tld/foo/bar  Oh yeah! look at this too: http://foobar.baz';
在此处插入神奇的正则表达式,然后

该阵列将如下所示:

theArray[0]='I am some text and check this out!  '
theArray[1]='http://blah.tld/foo/bar'
theArray[2]='  Oh yeah! look at this too: '
theArray[3]='http://foobar.baz'
我不知所措,任何帮助都将不胜感激

--Eric

被URL正则表达式拆分(感谢@Pullet在这里指出了一个缺陷):

让我们分解正则表达式:)

试试这个:

<script type="text/javascript">
    var url_regex = /((?:ftp|http|https):\/\/(?:\w+:{0,1}\w*@)?(?:\S+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:.?+=&%@!\-\/]))?)+/g;
    var input = "I am some text and check this out!  http://blah.tld/foo/bar  Oh yeah! look at this too: http://foobar.baz";

    var results = input.split(url_regex);
    console.log(results);
</script>

您也可以修剪单个结果,以避免在非url条目上出现前导和尾随空格。

您的意思是每次找到url时都应该拆分字符串吗?我知道字符串,我需要将其拆分,然后将其重新组合在一起,一遍又一遍,非常感谢-这就成功了!尽管我还在努力阅读它/(https*\:\/\/\S+[^\.\S+])/也将匹配httpssss://test.com 这不是有效的url。我想我们需要的是/(https?\:\/\/\S+[^\.\S+])/这个?这意味着前面的字符是可选的,但是如果您想支持其他协议,下面的类似内容也可以使用(取决于您需要支持的协议数量)/((https?| s?ftp | gopher)\:\/\/\s+[^\.\s+])/谢谢@Pullets,很好,做出了更改。我会让地鼠通过,不知道还有多少人还在使用它:0) (https? -> has "http", and an optional "s" \:\/\/ -> followed by :// \S+ -> followed by "contiguous" non-whitespace characters (\S+) [^\.\s+]) -> *except* the first ".", or a series of whitespace characters (\s+)
["I am some text and check this out!  ",
"http://blah.tld/foo/bar",
"  Oh yeah! look at this too: ",
"http://foobar.baz",
""]
<script type="text/javascript">
    var url_regex = /((?:ftp|http|https):\/\/(?:\w+:{0,1}\w*@)?(?:\S+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:.?+=&%@!\-\/]))?)+/g;
    var input = "I am some text and check this out!  http://blah.tld/foo/bar  Oh yeah! look at this too: http://foobar.baz";

    var results = input.split(url_regex);
    console.log(results);
</script>
["I am some text and check this out! ",
"http://blah.tld/foo/bar",
" Oh yeah! look at this too: ",
"http://foobar.baz", ""]