What is the difference between indexOf() and search()?

后端 未结 8 1968
情歌与酒
情歌与酒 2020-12-04 07:11

Being fairly new to JavaScript, I\'m unable to discern when to use each of these.

Can anyone help clarify this for me?

相关标签:
8条回答
  • 2020-12-04 07:44

    Without a regex, there is no practical difference between indexOf and search.

    The below example gives a live demo:

    function FromSearch() {
    
      var str = document.getElementById("demo").innerText;
      var n = str.search("difference");
      document.getElementById("Location").innerHTML = n;
    }
    
    function FromindexOf() {
      var str = document.getElementById("demo").innerText;
      var n = str.indexOf("difference");
      document.getElementById("Location").innerHTML = n;
    }
    <p id="demo">Without a <a href='http://www.w3schools.com/js/js_regexp.asp'>regex</a>, there is no practical difference between <a href='http://www.w3schools.com/jsref/jsref_indexof.asp'>indexOf</a> and <a href='http://www.w3schools.com/jsref/jsref_search.asp'>search</a>
    </p>
    
    <button onclick="FromSearch()">From search</button>
    
    <button onclick="FromindexOf()">From indexOf</button>
    
    <p>Location of difference in the above sentence is:</p>
    
    <mark id="Location"></mark>

    0 讨论(0)
  • 2020-12-04 07:47

    The search function (one description here) takes a regular expression, which allows you to match against more sophisticated patters, case-insensitive strings, etc., while indexOf (one description here) simply matches a literal string. However, indexOf also allows you to specify a beginning index.

    0 讨论(0)
提交回复
热议问题