D
D
Delakey Blackhole2017-06-07 21:45:30
JavaScript
Delakey Blackhole, 2017-06-07 21:45:30

js RegExp why not always one result?

20170607-tsoo-49kb.jpg
I don't understand why using one template and one text does not always produce the same result?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Sokolov, 2017-06-07
@DELAKEY

RegExp in JavaScript saves its state between calls. Since the expression contains the global match flag g, the search continues after the next match found.
An instance of a Regexp object has a lastIndex property that allows you to read/write the index at which the next match will start. It will help you figure out:

var RE = /([A-z0-9])/g;
console.log([
  RE.lastIndex, RE.test("aaaa"), // 0,true
  RE.lastIndex, RE.test("aaaa"), // 1,true
  RE.lastIndex, RE.test("aaaa"), // 2,true
  RE.lastIndex, RE.test("aaaa"), // 3,true
  RE.lastIndex, RE.test("aaaa"), // 4,false
  RE.lastIndex, RE.test("aaaa"), // 0,true
]);

S
Sergey Sobko, 2017-06-07
@Catzo0

Due to /g
https://stackoverflow.com/questions/1520800/why-re...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question