I have an input field where I'm entering any text including URLs inside it. If a long URL is entered is that text I want to shorten it (I'll be taking care of that via API).
HTML:
<input type="text" onKeyDown={this.onKeyDown(event)}/>
JavaScript:
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 url;
try {
url = new URL(stringWithURL); // This text includes simple text as well as URL as a string
if(url.protocol === "http:" || url.protocol === "https:") {
return this.convertLongURLtoShort(stringWithURL); // Call API function
}
} catch (e) {
return false;
}
}
}
However, the above function does not recognize simple text vs. a URL, as the input text takes the entire content as a single string. Hence it always goes into the failure function and I never get to convert URL into a short URL.
Is there a way to identify a text vs. a URL as we type into the input field (may be after hitting the space bar key or enter key) and call the API if the word entered by THE user is A URL?