SoFunction
Updated on 2025-03-03

javascript indexOf function usage instructions

How to use: (str,startIndex[optional])

Program code

Among them strObj is a must. String object or text.
str is a must. Substring to look for in the String object.
startIndex is optional. This integer value indicates the location where the search starts within the String object, starting from 0. If omitted, look up from the beginning of the string.


Note: indexOf for JavaScript is case sensitive.

The indexOf function method in JavaScript returns an integer value indicating the starting position of the substring inside the String object. If no string is found, return -1. If startindex is a negative number, startindex is treated as zero. If it is larger than the largest character position index, it is regarded as the largest possible index.

indexOf function executes search from left to right
The following example illustrates the usage of the indexOf function method.

Program code

var str1="fdiejDIFADF";
var str="e";
var i=(str);
alert(i);



As mentioned earlier, indexOf is case sensitive, and sometimes this causes us some trouble. So how to solve it? ? Of course, the easiest way is to convert the characters into uppercase or lowercase using toLowerCase or toUpperCase.
The code is as follows:

Program code

<script>
var Str = 'ABCDEF';
var Str1 = 'bcd';
alert(().indexOf(()));
str2 = 'AbCdEf';
alert(().indexOf(()));
</script>



The following method uses regularity to extend indexOf (from the network)

Program code

<script>
 = function(f,m){
var mm = (m == false) ? "i":"";
var re = eval("/"+ f +"/"+mm);
var rt = (re);
return (rt == null) ? -1:; 
}
var test = "absnegKIugfkalg";
alert(("kiu",false));
</script>



The following extension is even more powerful. It is compatible with the original indexOf function and can also perform searches that ignore sizes (also from the network).

Program code

<script language="javascript">
._indexOf = ;
 = function()
{
        if(typeof(arguments[ - 1]) != 'boolean')
                return this._indexOf.apply(this,arguments);
        else
        {
                var bi = arguments[ - 1];
                var thisObj = this;
                var idx = 0;
                if(typeof(arguments[ - 2]) == 'number')
                {
                        idx = arguments[ - 2];
                        thisObj = (idx);
                }

                var re = new RegExp(arguments[0],bi?'i':'');
                var r = (re);
                return r==null?-1: + idx;
        }
}
alert("bcssssasdfsdf".indexOf('A',3,true));
alert("bcssssasdfsdf".indexOf('a',3));
</script>