Search code examples
javascriptvar

add a piece of text to a variable if not included in the variable


I am trying to put a condition to check if the text variable starts with https:// or not. If not, I want to add https:// to the start of text.

 document.addEventListener("keydown", function (event) {
if (event.keyCode === 13) {
    var text = "https://" + document.getElementById("input").value;
    document.getElementById("iframe").src = text;
    document.getElementById("iframe").height = "100%";
    document.getElementById("iframe").width = "100%";
    document.getElementById("content").innerHTML = '';
}

});


Solution

  • Simply check if the input startsWith what you're looking for..

    let input = document.getElementById("input").value;
    let text = input.startsWith("https://") ? input : "https://" + input;
    

    As noted in the comments, the conditional ternary operator has been used here, you can find out more about it here: Conditional (ternary) operator