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>