代码之家  ›  专栏  ›  技术社区  ›  Ole Petersen

使用javascript在另一个字符串中查找字符串的位置

  •  0
  • Ole Petersen  · 技术社区  · 4 年前

    因此,我尝试创建一个函数,将字符串作为输入(通过按下按钮),例如“0211”,然后输出应该是位置。比如说288。这是我到目前为止所做的,但不起作用。有什么想法吗?非常感谢。

    function myFunction() {
      var str = "31415926...";
      var n = str.indexOf("BIRTHDAY");
      document.getElementById("demo").innerHTML = n;
    }
    <p>Click the button to enter your birthday.</p>
        
    <button onclick="myFunction()">Type your birthday</button>
        
    <p id="demo"></p>
    2 回复  |  直到 4 年前
        1
  •  1
  •   SuperDJ Franklin Rivero    4 年前

    请看以下内容:

    function myFunction() {
    let input = document.getElementById('birthday').value;
    let output = document.getElementById('demo');
    
    let str = '34534536456336345634634563456';
    
    output.textContent = str.indexOf(input);
    }
    <p>Click the button to enter your birthday.</p>
        
    <label for="birthday">Enter birthday</label>
    <input type="text" id="birthday">
    <button onclick="myFunction()">get position</button>
        
    <p id="demo"></p>