Home > front end >  How to get first URL contain in a string with JavaScript (Nodejs)?
How to get first URL contain in a string with JavaScript (Nodejs)?

Time:10-17

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

CodePudding user response:

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

CodePudding user response:

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'

  • Related