简体   繁体   中英

How does .index work when I use it on the .exec() result in Javascript?

I'm working on a program that extract information from a large chuck of text using javascript and while looking at a former co-workers code of something similar I found that when you save the result of .exec() and do .index of that variable it gives you the index of that substring in the array.

Example:

var str="I found this for you!";
var pattern=/this/igm;
var result=pattern.exec(str);
document.write("\"This\" Index = " +  result.index + ".");

Result:

"This" Index = 8.

When I looked online I found that exec() returns an array and it looks like arrays don't have an .index property. All my searches of .index seem to come up index().

What is going on here? Why does this work? I'm also wondering if there are some other things I can do related to this (like .lastindex).

index is a special property added to the array by exec . It does not necessarily have to be there by default, and reproducing the behaviour yourself is quite easy.

var example = [1, 2, 3];
example.index = 15;

Here is a great resource on what exec does. It not only returns an array with extra properties like index , but it also modifies the regex object that was used.

Try this:

var str="I found this for you!";
var pattern=/this/igm;
var result=pattern.exec(str);
for(var i in result){
    console.log("i: " + i);
    console.log("result[" + i + "]: " + result[i]);
}

// i: 0
// result[0]: this
// i: index
// result[index]: 8
// i: input
// result[input]: I found this for you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM