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?
The search method The indexOf method on strings cannot be called with a regular expression.
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.
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.
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.
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
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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With