Replace () as call back function

We know that the replace() method will return a new string based on the pattern and its corresponding replacement argument.

Here the pattern can be either general string or regular expression that we normally use. And for replacement argument in most cases we use string as replacement. But there is an extensible facility to use this replacement as call back function.

Here we go with a small example code snippets.

Code Snippets:


var numbers = '34 55 27 45 72',
type1 = numbers.replace(/\d+/g, '*'),
type2 = numbers.replace(/\d+/g, function (item) {
return +item < 50 ? '*' : item;
});
console.log("simple replace() : ", type1);
console.log("replace() with call back function : ", type2);

Fiddle Demo

Note:

The call back function will be invoked for the each matched set of an item, when the first parameter regular expression is declared as global.

Advertisements

Deleter – Node based directory removing tool

My first node package deleter, has been released. Its a CLI, which is used to remove directories. I come up with idea to create this when i faced difficulties in deletingĀ node_modulesĀ from my node based applications.

Installation

npm install deleter -g

Since it is a CLI, global installation is preferred.

Usage

deleter <directory-name>

Example


deleter node_modules

Limitations

For now, its target for windows operating system and other OS will be considered in upcoming updates.