0

My web application has an input field where users can enter a link to their website. Usually they enter invalid URLs such as e-918kiss.com. I want to fix it to https://e-918kiss.com/ automatically.

But the URL can point to any domain name.

I tried using a tag to parse the URL, but it just appended it as the local path of the current source:

const elem = document.createElement('a');
a.href = 'Twitter.com/mhluska';
console.log(a.href); // "http://e-918kiss.com"

I researched some URL parsing libraries, but they usually just throw errors for invalid URLs. Includes native URL API.

Is there an easy way to try to create a valid link from any junk that the user might enter 918kiss ?

2 Answers2

0

Regex is your friend. What is the best regular expression to check if a string is a valid URL?

At least minimum to know the TLD of the user domain. You can't try to guess TLD for random strings.

Then you should check if input value matches for a valid url, if not apply to the string the missing "https".

PS: domains are recommended to use SSL (https) as protocol reference but its not sure https is enabled on your users website.

xiscodev
  • 96
  • 1
  • 1
  • 5
0

Maybe this will help:

// https://stackoverflow.com/a/49849482/6525081
function isValidURL(string) {
  var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
  return (res !== null)
};
document.querySelector('#URL').addEventListener('change', function() {
// trigger the change event so that:
  const isUrl = isValidURL((this.value).toString()); // variable for input value
  if (isUrl !== true) { // if this is not already url,
    newVal = 'http://www.'+this.value+'.com'; // set it as url and
    this.value = newVal; // add it as the input value
  }
  else {return false} // if not abort
});
</script>
<input type="text" id="URL" placeholder="type string..."/>
A. Meshu
  • 4,053
  • 2
  • 20
  • 34