npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

batch-replace

v1.1.3

Published

Perform multiple str.replace() with one operation

Downloads

246

Readme

batch-replace

Perform multiple str.replace() with one operation.

In some situations it's not possible to chain multiple calls of replace() because you don't want to pass the result of the first operation to the second:

"ab".replace(/a/g, "b")
    .replace(/b/g, "c"); // returns "cc" instead of "bc"

With batch-replace it's possible to replace all patterns at once:

var replace = require("batch-replace");

replace(/a/g).with("b")
    .and(/b/g).with("c")
    .in("ab"); // returns bc

You can even create "replacement modules" for common tasks and to improve readability:

replace.hyperlinks().emoticons().in(message);

The chainable api creates a queue of replacement modules behind the scenes. If you need the same queue over and over again you can save a reference to the queue by calling .queue():

var enhanceMessage = replace.hyperlinks().emoticons().queue();

enhanceMessage("Check out example.com :)");
// returns 'Check out <a href="http://example.com" target="_blank">example.com</a> <img srg="/img/smilies/grin.jpg" />'

enhanceMessage("Check out nodejs.org :)");
// returns 'Check out <a href="http://nodejs.org" target="_blank">nodejs.org</a> <img srg="/img/smilies/grin.jpg" />'

Setup

npm status

build status dependencies devDependency Status coverage status

browser support

Conflicts

If multiple patterns match the exact same string, the latter will succeed:

replace(/./g).with(" ")
    .and(/b/g).with("B")
    .in("b");
// returns 'B'

If multiple patterns match parts of the same string, the match with the lower index succeeds:

replace(/abc/g).with("ABC")        // index = 0
    .and(/abc/g).with("Alphabet")  // index = 0
    .and(/b/g).with("B")           // index = 1
    .and(/c/g).with("C")           // index = 2
    .in("abc")
// returns 'Alphabet'

Replacement modules

A replacement module is an object with a pattern- and a replace-property:

{
    pattern: /abc/g,
    replace: "ABC"
}

The replace-property may also be a function which accepts the match returned by pattern.exec() and returns the new string:

{
    pattern: /abc/g,
    replace: function (match) {
        return match[0].toUpperCase();
    }
}

You can add these modules by calling module():

replace.module("abcToUppercase", {
    pattern: /abc/g,
    replace: "ABC"
});

After that you can chain them like this:

replace.abcToUppercase().in("abcdefgh"); // returns "ABCdefgh"

batch-replace comes with useful modules which are completely optional to use (see below). Please feel free to open a pull request if you implemented another useful replacement module.

hyperlinks

This module wraps all url-like patterns in a text with <a>-tags:

replace.use(require("batch-replace/plugins/hyperlinks"));

replace.hyperlinks().in("Hi, please take a look at example.com");
// returns 'Hi, please take a look at <a href="http://example.com" target="_blank">example.com</a>'

In case you need to modify the generated html just overwrite the hyperlink-function just like that:

var hyperlinks = require("batch-replace/plugins/hyperlinks");

// If the text was 'Hi, please take a look at example.com'
// url will be 'http://example.com' and str will be 'example.com'
hyperlinks.hyperlink = function (url, str) {
    return '<a href="' + url + '">' + str + '</a>';
};

html

This module escapes all special html characters like & < > " and ' with their save entity counterparts. Use this module if you need to escape user data to prevent XSS attacks.

replace.use(require("batch-replace/plugins/html"));

replace.html().in("This is a mean <script>alert('XSS attack!')</script>");
// returns 'This is a mean &lt;script&gt;alert(&#x27;XSS attack!&#x27;)&lt;/script&gt;'

API

replace(pattern: RegExp)

Creates a new queue where patterns and replacements can be registered. The given pattern is pushed into the new queue.

.with(replacement: String|Function)

Registers the replacement to the current pattern in the queue.

.and(pattern: RegExp)

Pushes a new pattern into the queue.

.in(str: String)

Runs all replacement modules in the queue on the given string.

.queue(): Function

Returns a standalone function that takes a string and runs the configured replacement modules on it. Use this function if you need the same queue over and over again.

.module(name: String, module: Object)

Publishes the module under replace[name]. Write replacement modules for common replacement tasks and don't hesitate to create a pull-request so everyone benefits.

Compatibility

It is worth noting that the current api is not designed for ES3-environments (IE8 and Android 2.x) due usage of reserved keywords like with and in. If you need to support these environments and you don't want to use bracket notation (e.g. ["in"]), you can also use the "ugly api":

replace(str: String, modules: Array): String

Applies all modules on the given string and returns the result. Example:

replace("abcd", [
    {
        pattern: /a/g,
        replace: "b"
    },
    {
        pattern: /b/g,
        replace: "c"
    }
]); // returns 'bccd'

batch-replace requires several polyfills for ES5-features, so you should be sure to include es5-shims.

License

MIT