Notes

JavaScript - Regular Expression 'g' flag

author: Paul Kim

categories: js, regex

tags: js, regex

Title

The "g" flag indicates a global match (i.e., find all matches rather than stopping after the first match)

But we need to be careful when using this flag with RegExp.prototype.test() and RegExp.prototype.exec() methods

todo:

  • talk about global property of regex (i.e., var regex = new Regex('foo', 'g'); var g = regex.global; // true)
  • talk about lastIndex property of regex and how it can cause potential issue with the "g" flag if we are not careful
var str = 'table football'

var regex = RegExp('foo*')
var globalRegex = RegExp('foo*', 'g')

console.log(globalRegex.test(str)) // true
var str = 'table football'

var regex = RegExp('foo*')
var globalRegex = RegExp('foo*', 'g')

console.log(globalRegex.test(str)) // true
console.log(globalRegex.test(str)) // false
var str = 'table football table football'

var regex = RegExp('foo*')
var globalRegex = RegExp('foo*', 'g')

console.log(globalRegex.test(str)) // true
console.log(globalRegex.test(str)) // true
var str = 'table football table football'

var regex = RegExp('foo*')
var globalRegex = RegExp('foo*', 'g')

console.log(globalRegex.test(str)) // true
console.log(globalRegex.test(str)) // true
console.log(globalRegex.test(str)) // false
var str = 'table football table football table football'

var regex = RegExp('foo*')
var globalRegex = RegExp('foo*', 'g')

console.log(globalRegex.test(str)) // true
console.log(globalRegex.test(str)) // true
console.log(globalRegex.test(str)) // true

https://2ality.com/2013/08/regexp-g.html

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Parameters


ChromeEdgeFirefoxOpera

© 2021 paulkode.com. All rights reserved.