Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Monday, December 14, 2015

In Javascript, what is the difference between indexOf() and search()?

In Javascript, what is the difference between indexOf() and search()?


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

Can anyone help clarify this for me?

Answer by Greg for In Javascript, what is the difference between indexOf() and search()?


indexOf is for plain substrings, search can do regular expressions.

Answer by ng.mangine for In Javascript, what is the difference between indexOf() and search()?


If you require a regular expression, use search(). Otherwise, indexOf() is going to be faster.

Answer by CMS for In Javascript, what is the difference between indexOf() and search()?


I think the main difference is that search accept regular expressions.

Check this reference:

Answer by joel.neely for In Javascript, what is the difference between indexOf() and search()?


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.

Answer by LeppyR64 for In Javascript, what is the difference between indexOf() and search()?


Search finds it's matches with a regular expression, but has no offsets. IndexOf uses literals to match, but has an offset.

IndexOf

Search

Answer by student for In Javascript, what is the difference between indexOf() and search()?


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;  }

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

Location of difference in the above sentence is:


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 71

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.