Is it possible to convert a text to URL format using javascript

Viewed 296

Basically I want to know that how to build code snippet so that when a user input text and click on the submit button. Automatically add https:// as prefix and .com as suffix and build a valid urls using javascript. And that result should be visible right below the form.

Can anyone help me

3 Answers

Mate, I don't know if you know this but not all sites end with ".com" some of them might end with ".edu", ".in", ".io", ".org" etc. Also, some URLs start with "blob:https://" and things like that. I think you probably would need an API.

Yes, it is possible, you just add a keyup or change event listener on the input, and concatenate the text from the input with what you need. Here's an example:

// HTML
<div class="container">
    <input type="url" id="url-maker" />
    <p class="url-output"></p>
</div>
// JS
const urlInput = document.getElementById('url-maker');
const urlOutput = document.querySelector('.url-output');

urlInput.addEventListener('keyup', (event) => {
    let urlText = event.target.value;
    if (!urlText.includes('https://')) {
        urlText = `https://${urlText}`;
    }
    if (!urlText.includes('.')) {
        urlText = `${urlText}.com`;
    }
    urlOutput.innerText = urlText;
});

However, you do need to properly validate the strings and also keep in mind that domains end in other extensions than .com! What I've showed you is just a basic example!

Try this out, it take input and covert it to a link by adding https:// and .com

To see it working here just type input as: stackoverflow. If you want to test it with other sites, copy and use the code locally.

function urlMaker(){
  var linkVal=document.getElementById("inputText").value;
  var href =  document.getElementById('aLink').href="https://"+linkVal+".com";
  document.getElementById("aLink").innerHTML = href;
 }
<input name="inputTxt" type="text" id="inputText">
<button onclick="urlMaker()">Get Link</button>
<br><br>
<a href="#" id="aLink"></a>

Related