1

I make an example here:

var reg = /\s+/g;

function testfn() {

  // reg = /\s+/g;

  var res = reg.test('mike ross');

  var showEle = document.querySelector("#show");
  showEle.innerHTML = res;

}
<button onclick="testfn()">click</button>
<span id="show"></span>

as you can click the button, and will find there's different result when you click again and again.

but defined the regex in function inside (comment the line inside),then you found it work as before.

why???

3
  • 1
    We stop you using jsfiddle directly because we want the question to be self-contained. The code should be posted here. Commented Feb 12, 2016 at 5:57
  • oh~,i see, will do it next time,thanks for copy the code!! Commented Feb 12, 2016 at 6:05
  • See meta.stackoverflow.com/questions/270944/… for how to create a Stack Snippet, which is like jsfiddle but built into SO. Commented Feb 12, 2016 at 6:06

2 Answers 2

2

Regular expression objects using the g flag have state, so that you can loop through all matches in a string. When you use the same object again, it continues from where it left off. When you create a new one each time (by creating it in the function), it starts at the beginning each time.

The state is in the lastIndex property, which (despite the name) says where to begin matching next time. Here's your example reusing the same global object, and showing lastIndex after each operation:

var reg = /\s+/g;

function testfn() {

  var str = "Matching starting at " + reg.lastIndex;

  var res = reg.test('mike ross');

  var showEle = document.querySelector("#show");
  showEle.innerHTML = str += ", res = " + res;
}
<button onclick="testfn()">click</button>
<span id="show"></span>

Vs. creating a new object every time:

function testfn() {

  var reg = /\s+/g;
  var str = "Matching starting at " + reg.lastIndex;

  var res = reg.test('mike ross');

  var showEle = document.querySelector("#show");
  showEle.innerHTML = str += ", res = " + res;
}
<button onclick="testfn()">click</button>
<span id="show"></span>

Sign up to request clarification or add additional context in comments.

Comments

0

It's because of the g modifier. This modifier makes the regexp remember the place where it last matched, and every time you use it it looks for the next match after that.

With the global variable, there's just one RegExp object, and it remembers its position across all the calls to the function.

With a local variable, the RegExp object gets recreated every time you call the function, so it starts looking from the beginning of the string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.