In this case, I suggest to use a regex to split URL(s) based on the input string.
The pattern can be found here:
https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
Also, in your example string, because there is some URL which ends with a dot (.) character, you need to remove that last character.
function onKeyDown(event) {
var stringWithURL = "Hello, World! https://www.google.com. I'm delighted to be a part of \"https://amazon.com\". Come again";
if (event.keyCode === 32 || event.keyCode === 13) { // Space bar and enter keys
let pattern = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g
let urls = stringWithURL.match(pattern);
for (let url of urls) {
if (url.endsWith('.')) {
// Removing the last character if the URL ends with a dot
url = url.slice(0, url.length - 1);
}
// Parsing to URL
url = new URL(url);
if(url.protocol === "http:" || url.protocol === "https:") {
console.log(url);
}
}
}
}
<input type="text" onKeyDown="onKeyDown(event)"/>
CLICK HERE to find out more related problems solutions.