简体   繁体   中英

How to extract an HTTP URL using vanilla Javascript?

I want to extract the first URL https://example.com/ccm/resource/itemName/com.ibm.team.workitem.Attachment/72306 from the following string using vanilla 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);

What would be a good search command or regex? Please note that there is a second URL-like string later in the string that I don't want to extract.

It's not regex but here is a solution :

 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);

I first split the string on "href=", then I take the second part of the split, remove the first quote and split again on quote

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM