javascript - 从字符串中提取域

标签 javascript

如何从 JS 中的字符串中提取域,因此对于下面列表中的每个字符串,输出将为 example.com,但最后两个字符串的输出应为 null 或未定义或空字符串。我基本上只是尝试从字符串中提取域,下面是验证它的测试用例。

var urls = [
    "case 1 http://example.com",
    "case 2 https://example.com",
    "case 3 custume_scheme://example.com",
    "case 4 www.example.com",
    "case 5 www.example.com/staffToIgnore",
    "case 6 www.example.com?=key=leyToIgnore",
    "case 7 www.example.com ignore all those too",
    "case 8 www.example.com www.example2.com",
    "case 9 example.com need to return null",
    "case 10 wwwa.example.com need to return null",
];
  • 域的扩展名可以是其他东西 .com ,它可以是 [a-z0-9] 形式的任何内容
  • 允许子域。

有几个与此类似的问题,但没有一个具体,也没有一个答案通过了这里的所有案例。

最佳答案

您可以使用Lodash轻松实现您所需要的。如果您要丢弃所有包含格式错误的域的字符串,那么我设置 this plunker which tells you which strings contain a domain.

var urls = [
        "case 1 http://example.com",
        "case 2 https://example.com",
        "case 3 custume_scheme://example.com",
        "case 4 www.example.com",
        "case 5 www.example.com/staffToIgnore",
        "case 6 www.example.com?=key=leyToIgnore",
        "case 7 www.example.com ignore all those too",
        "case 8 www.example.com www.example2.com",
        "case 9 example.com need to return null",
        "case 10 wwwa.example.com need to return null",
];

_.forEach(urls, function(currentS){
  //If currentS is indeed a string
  if(_.isString(currentS)){
     //If it is a url
     if(isUrl(currentS)){
       $('#urls_list' ).append('<li>'+  currentS.match(/([a-zA-Z])*\.([a-zA-Z]){0,3}(?=\s|\?|\/|$)/)[0] +'</li>');
     } else {
       $('#urls_list' ).append('<li> null </li>');
     }
  }
});

其中isUrl

//Returns true if current string s is a domain else false
function isUrl(s){
  if(_.includes(s, 'www.', '.com') || _.includes(s, '://', '.com')){
     return true
  } else {
     return false;
  }
}

输出:

enter image description here

currentS.match(/([a-zA-Z])*\.([a-zA-Z]){0,3}(?=\s|\?|\/|$ )/)[0] 仅返回您正在查找的内容:

  • ([a-zA-Z])*\.:域。
  • ([a-zA-Z]){0,3}:com
  • (?=\s|\?|\/|$)/) :匹配 ? 的前瞻>/ 或字符串结尾
  • [0]:获取第一个匹配

无论如何,如果我是你,我会看一下 validator这是一个很棒的检查字符串的库。它有一个方法 isUrl 可以明确告诉您字符串是否包含 url。我无法将其导入到 plunker 中,因此我创建了一个自定义函数。

你可以看看_.includes here并到 _.forEach here .

如果您想使用正则表达式而不是第二个 _.forEach_.includes,请查看 this answer作者:@Daveo。

关于javascript - 从字符串中提取域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42818165/

相关文章:

javascript - 在某个点停止/禁用垂直滚动,但能够向上滚动页面但不能向下滚动

javascript - new Date() 返回相对时间而不是 UTC 时间

javascript - 如何更改 WordPress 发件人姓名?

javascript无法使用double来获得总和

javascript - 将 HTML 本地存储中的项目获取到 HTML 表中

javascript - 为什么许多网站缩小 CSS 和 JavaScript 而不是 HTML?

javascript - 使用 Twitter Flight 将组件附加到动态创建的元素

javascript - 在php中完成表单提交后是否可以重定向回来?

javascript - 示例 jquery 获取 sibling 的索引/位置

javascript - 如何在javascript中获取数组中的json值