'Why url is converted into sub-url in HTML when passing through input field? [duplicate]

I am taking URL as input from user in HTML form and creating a dynamic link with javascript. The code is working fine when I am giving input as "https://www.google.com" but when I am passing input as something like "google.com" it is converting link to localhost path eg file:///path_where_html_exists/urlpassed here is my code

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <form>
      <input id="inputurl" type="url" />
      <button type="submit" onclick="handleSubmit()">sunmit</button>
      <script src="newscript.js"></script>
    </form>

    <div id="newpara"></div>
  </body>
</html>

JS

function handleSubmit() {
  event.preventDefault()
  var elem = document.getElementById('inputurl').value
  console.log(elem)
  ele = document.getElementById('newpara')
  ele.innerHTML += `<a href="${elem}">link here</a>`
}

Thanks



Solution 1:[1]

If you put a text inside the "href" attribute of a link, and that text doesn't have a protocol at the beginning (either http or https, or similar) the browser will append it to the end of the current page url.

You can see that in action in this JSFiddle. Since you were testing it on your pc by opening the file in a browser, you see the url you mentioned.

To fix it, just check if the text has a protocol or not, and insert it when necessary. A very basic implementation could look like this:

if (!elem.startsWith("http")) {
  elem = "//" + elem;
}

This fiddle will show you how.

Here it is also a better implementation using regex:

let reg = /^http(s)?:\/\//g;
if (!elem.match(reg)) {
  elem = "//" + elem;
}

Solution 2:[2]

Tried to add "http://" or "https://" before the inputed url seems work

function handleSubmit() {
  event.preventDefault()
  var elem = document.getElementById('inputurl').value
  console.log(elem)
  ele = document.getElementById('newpara')
  ele.innerHTML += `<a href="http://${elem}">link here</a>`
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Raku-Seru