代码之家  ›  专栏  ›  技术社区  ›  JJD

如何使用普通JavaScript提取HTTP URL?

  •  -5
  • JJD  · 技术社区  · 7 年前

    我想提取 第一 统一资源定位地址 https://example.com/ccm/resource/itemName/com.ibm.team.workitem.Attachment/72306 使用普通的javascript从下面的字符串。

    var str = '<a href="https://example.com/ccm/resource/itemName/com.ibm.team.workitem.Attachment/72306" data-cke-rtc-autolink="true" data-cke-rtc-autolink-text="Anhang 72306" data-cke-rtc-autolink-url="/ccm/resource/itemName/com.ibm.team.workitem.Attachment/72306" class="jazz-ui-ResourceLink" id="jazz_ui_ResourceLink_23" widgetid="jazz_ui_ResourceLink_23">Anhang 72306</a>';
    
    var pattern = /^http(.*?)(")/g;
    var match = pattern.exec(str);
    alert(match);

    什么是好的搜索命令或regex?请注意,在后面的字符串中还有第二个类似URL的字符串,我不想提取它。

    1 回复  |  直到 7 年前
        1
  •  1
  •   toto1911    7 年前

    它不是regex,但这里有一个解决方案:

    var str = '<a href="https://example.com/ccm/resource/itemName/com.ibm.team.workitem.Attachment/72306" data-cke-rtc-autolink="true" data-cke-rtc-autolink-text="Anhang 72306" data-cke-rtc-autolink-url="/ccm/resource/itemName/com.ibm.team.workitem.Attachment/72306" class="jazz-ui-ResourceLink" id="jazz_ui_ResourceLink_23" widgetid="jazz_ui_ResourceLink_23">Anhang 72306</a>';
    
    var url = str.split('href=')[1].substring(1).split('"')[0];
    alert(url);

    我首先在“href=”上拆分字符串,然后在拆分的第二部分中删除第一个引号,然后在引号上再次拆分。