re: TIL: JavaScript replace() command with callback VIEW POST


Yes, replace with a callback is pretty powerful. However, keep in mind that regular expressions are meant to solve regular problems and will easily fail on irregular tasks.

Also, your understanding of the syntax is slightly imcomplete, it actually is:

String.prototype.replace(regExp, callback(
  fullMatch: string,
  ...capturedMatches: string[],
  positionOfFullMatchInString: number,
  inputString: string

Captured matches are what you get from using parentheses in your RegExp. The position in the string like all string functions in JS counts UTF-16/-32 chars as multiple characters. Unlike a lot of other methods, the callback is not run in the scope of the object it is called on, so this will default to the global scope unless manually bound.

code of conduct - report abuse