简体   繁体   中英

How to get first URL contain in a string with JavaScript (Nodejs)?

In Node.js I have a string like below but i don't know how to get first URL contain inside that string:

"

<p> You left when I believed you would stay. You left my side when i needed you the most</p>**<img src="https://cloud-image.domain-name.com/storage/images/2021/picture_01.png" />** <br/> <p>Today, I don't have any bad words for you. I just want to thank you</p> **<img src="https://cloud-image.domain-name.com/storage/images/2021/picture_02.jpg" />

I want to get one result:

https://cloud-image.domain-name.com/storage/images/2021/picture_01.png

This is a bit of a workaround, however, you can scan the string you get

var matches = string.match(/\\bhttps?:\\/\\/\\S+/gi);

then just do matches[0], however a few things work around this so alternatively, you could use a library such as URL Knife if you want a robust method with a library.

https://github.com/Andrew-Kang-G/url-knife

The indexOf() method returns the index of the first occurrence. You can learn more about string methods on w3schools

const a = `<p> You left when I believed you would stay. You left my side when i needed you the most</p>**<img src="https://cloud-image.domain-name.com/storage/images/2021/picture_01.png" />** <br/> <p>Today, I don't have any bad words for you. I just want to thank you</p> **<img src="https://cloud-image.domain-name.com/storage/images/2021/picture_02.jpg" />`

const start=a.indexOf("https") //To get the index of the first link. (Returns 104)
const end=a.slice(start).indexOf('" />') //To get the end index of end link (Returns 70)
a.slice(start,start+end) //Returns 'https://cloud-image.domain-name.com/storage/images/2021/picture_01.png'

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