Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex used in javascript array indexOf

I need to find the index of the word in array .But for the following scenario

var str="hello how are you r  u fineOr not .Why u r not fine.Please tell wats makes u notfiness".
var splitStr=str.split(" ");
//in splitStr array fineOr is stored at da index of 6.
//in splitStr array notfiness is stored at da index of 18.
var i=splitStr.indexOf("**fine**");
var k=splitStr.lastindexOf("**fine**");
console.log('value i-- '+i); it should log value 6
console.log('value k-- '+k); it should log value 18

How do I need to pass the regex for searching the string "fine" for the function indexOf of array?

like image 547
Pravin Reddy Avatar asked Nov 25 '13 09:11

Pravin Reddy


People also ask

Does indexOf take regex?

The search method The indexOf method on strings cannot be called with a regular expression.

Can you use indexOf in an array?

indexOf() The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Is indexOf faster than regex?

Contains and String. IndexOf is only useful for checking the existence of an exact substring, but Regex is much more powerful and allows you to do so much more.

How does array indexOf work?

In its simplest version, the indexOf method takes one argument which is the element we are trying to find. Then it returns the index of the first element it finds in the array which satisfies el === target . This means that even if there are two matches in your array, indexOf will only return one result.


2 Answers

After .split(' ') you will get splitStr as an array , so you have to loop through that

 var str="hello how are you r  u fineOr not .Why u r not fine.Please tell wats makes u notfiness";
 var splitStr = str.split(" ");
 var indexs = [];
 splitStr.forEach(function(val,i){

     if(val.indexOf('fine') !== -1) {  //or val.match(/fine/g)
        indexs.push(i);
     }
 });

console.log(indexs) // [7, 13, 18]

console.log('First index is ', indexs[0]) // 7
console.log('Last index is ', indexs[indexs.length-1]) // 18
like image 35
Sarath Avatar answered Oct 18 '22 20:10

Sarath


You can also use filter on the array of words,

http://jsfiddle.net/6Nv96/

var str="hello how are you r  u fineOr not .Why u r not fine.Please tell wats makes u notfiness";
var splitStr=str.split(" ");
splitStr.filter(function(word,index){
    if(word.match(/fine/g)){/*the regex part*/
    /*if the regex is dynamic and needs to be set by a string, you may use RegExp and replace the line above with,*/
    /*var pattern=new RegExp("fine","g");if(word.match(pattern)){*/

        /*you may also choose to store this in a data structure e.g. array*/
        console.log(index);
        return true;
    }else{
        return false;
    }
});
like image 153
melc Avatar answered Oct 18 '22 21:10

melc