如何通过字符串中的URL拆分字符串?

时间:2018-06-20 21:06:00

标签: javascript regex url

我想根据字符串中的URL将字符串拆分为字符串数组。

例如,如果我的字符串是

“您好,这是字符串https://www.google.com,更多内容www.address.co句子结尾。”

那我想得到

[“您好,这是一个字符串”,“ https://www.google.com”,“更多内容”,“ www.address.co”,“句子结尾”。]

function split(s) {
  const pattern = new RegExp(
    "(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,}/)"
  )
  return s.split(pattern)
} 

不确定为什么这对我不起作用。我得到这个:

[“您好,这是一个字符串”,“ https://www.google.com更多”,“这是www.address.co句子的结尾。”]

1 个答案:

答案 0 :(得分:0)

首先,您需要对正则表达式进行两次转义,因为您将其作为要解析的字符串进行传递。

然后,您还需要使最后的/为可选(,并将其添加到第一种情况下

如此

function split(s) {
  const pattern = new RegExp( "(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,}/?)" );
  return s.split(pattern)
}

console.log( split('Hello this is a string https://www.google.com more stuff www.address.co end of sentence.') );


如果您使用的是正则表达式文字,那么它几乎可以直接工作(您需要转义/

function split(s) {
  const pattern = /(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,}\/?)/;
  return s.split(pattern)
}

console.log( split('Hello this is a string https://www.google.com more stuff www.address.co end of sentence.') );