RegExp spec question

2014-07-16 Thread Alex Vincent
r = /\u0020+$/g; p = r.exec( ); q = r.exec( ); JSON.stringify([p, q]) // [[\ \],null] Why does calling exec the second time generate null? When I try the regular expression without the /g flag, I get: // [[\ \],[\ \]] -- The first step in confirming there is a bug in someone else's work

Re: RegExp spec question

2014-07-16 Thread Andrea Giammarchi
expected by specs ... try this r = /\u0020+$/g; p = r.exec( ); r.lastIndex = 0; q = r.exec( ); alert(JSON.stringify([p, q])) and you are good to go ... without resetting lastIndex, you can also use .replace(r, 'whatever') and it's going to work every time. Have a look at these slides to

Re: RegExp spec question

2014-07-16 Thread Axel Rauschmayer
Yes, the /g flag is confusing, because the regular expression kind of turns into an iterator. I’d much prefer an actual iterator-based API that doesn’t mutate the regular expression. On Jul 16, 2014, at 9:26 , Alex Vincent ajvinc...@gmail.com wrote: r = /\u0020+$/g; p = r.exec( ); q =

Re: RegExp spec question

2014-07-16 Thread Frankie Bagnardi
You could wrap it in an iterator :-) http://www.es6fiddle.net/hxoczoqg/ ```javascript function* match(regex, haystack){ var {source, ignoreCase} = regex; var newRegex = new RegExp(source, ignoreCase ? 'gi' : 'g'); var m = null; while (m = newRegex.exec(haystack)) { yield m; } } var

Re: RegExp spec question

2014-07-16 Thread Andrea Giammarchi
you can also use this code ... like today, with every browser, and right away ... ```javascript function match(regex, haystack){ var result = [], g = regex.global, match; do { match = regex.exec(haystack) } while(match result.push(match) g); if (!g) regex.lastIndex = 0; return

Re: Re: RegExp spec question

2014-07-16 Thread Виктор Мухачев
function* match(regex, haystack){ var {source, ignoreCase} = regex; var newRegex = new RegExp(source, ignoreCase ? 'gi' : 'g'); var m = null; while (m = newRegex.exec(haystack)) { yield m; } } this code is not best in that case: var regex = /\d+/; var first = match(regex, 1 2 3 4);