1

Here is the output from my browsers console. This regex checks for doubled_words, looks for occurrences of words (strings containing 1 or more letters) followed by whitespace followed by the same word.

var reg=/([A-Za-z\u00C0-\u1FFF\u2800-\uFFFD]+)\s+\1/gi;
undefined
reg.test("sdfs sdsdf")
true
reg.test("sdfs sdsdf")
false

the result is true alternate times, why is this weird behavior?

Darshan N Reddy
  • 229
  • 2
  • 10
  • possible duplicate of [Regular Expression For Consecutive Duplicate Words](http://stackoverflow.com/questions/2823016/regular-expression-for-consecutive-duplicate-words) – Ole Spaarmann Jun 19 '15 at 14:26

1 Answers1

2

That behavior is due to use of global flag. Remove it

var reg=/([A-Za-z\u00C0-\u1FFF\u2800-\uFFFD]+)\s+\1/;

Using g causes regex state (lastIndex value) to be remembered across multipel calls to test or exec methods.

Check this official reference Read the Description section.

anubhava
  • 664,788
  • 59
  • 469
  • 547