-2

I have some string below. I need a regex string matching all urls with a specific string in domain name. In the example string, i want to match all urls "example" domains regardless of their dot extensions.

Example string

    http://example.net/file/25404c920e2a5501fbb660ba1c093e59 http://notexample.com/view/858BA4159ED9B53
  <br>https://example.com/file/08558aa484fb1327d215fc6ce19da601/Transform.html
  <b>http://notexample.com/view/567</b>
senbon
  • 766
  • 5
  • 12

2 Answers2

1

So at first look, your .innerHtml should be .innerHTML. Capitalize the HTML and then the .match will work correctly. That will return an array of everything that matches your regex.

We then loop over that and use .includes method to find any URL that includes what it is your trying to find in the URLs.

Keep in mind that .includes will find any string that INCLUDES what you specify so even your examples that say 'notexample' will also be return into this final array. If you change your 'notexample' to something that doesn't contain 'example', it should work fine.

const urlRegex = new RegExp(`((https?|):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])`, 'ig');

const urls = document.querySelector('div').innerHTML.match(urlRegex);

let selectedURLs = []

for (let i = 0; i < urls.length; i++) {
  if (urls[i].includes('example')) {
       selectedURLs.push(urls[i])
  }
}

console.log(selectedURLs)
0

It's difficult to understand what you are asking here, but I will give it my best shot. It seems you are trying to parse URLs in Javascript, if so this post provides a function for doing so. You could pass your strings through your URL regex to verify that they are valid URLs before using this to parse them.

Examples:

var l = getLocation("http://example.com/path");
console.debug(l.hostname)
>> "example.com"
console.debug(l.pathname)
>> "/path"