如果不包含在变量中,则将一段文本添加到变量中

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

我试图设置一个条件来检查 text 变量是否以 https:// 开头。如果没有,我想在 text.

的开头添加 https://
 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 = '';
}

});

只需检查输入startsWith是否是您要查找的内容..

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

如评论中所述,此处使用了条件三元运算符,您可以在此处找到更多相关信息:Conditional (ternary) operator

一种方法是:

// here we cache the value of the <input> element:
let value = document.getElementById("input").value,
    // we define the protocol we're looking for:
    protocol = 'https://',
    // we then assign the text, using a template-literal string,
    // first we use a conditional operator:
    // which returns a Boolean (true/false), if the
    // String we test starts with the supplied String
    // ('protocol'); if it does we return an empty string
    // and if not we return the protocol variable; and then
    // that's concatenated with the existing 'value'
    // variable:
    text = `${value.startsWith(protocol) ? '' : protocol}${value}`;

参考文献:

尝试使用 includes 函数来检查字符串是否包含另一个字符串。

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