Git Product home page Git Product logo

frep's Introduction

frep NPM version

Find, replace and string tranformation utility for node.js. Modify strings by passing an array or object of RegExp or string replacement patterns. Patterns can be strings, arrays of strings or regex, replacements can be strings or functions.

Quickstart

Install with npm:

npm i frep --save-dev

Usage:

var replace = require('frep');

// Patterns can be strings, regex or arrays.
// Replacements can be strings or functions.
var replacements = [
  {
    pattern: 'a',
    replacement: 'x'
  },
  {
    pattern: /b/,
    replacement: 'y'
  },
  {
    pattern: /c[\S]+/,
    replacement: function(match) {
      return match.toUpperCase();
    }
  }
];

console.log(replace.strWithArr('abcdefg', replacements));
//=> 'xyCDEFG'

API

// Transform a string with an array of replacement patterns
replace.strWithArr(String, replacements);
// Transform an array of strings with an array of replacement patterns
replace.arrWithArr(Array,  replacements);
// Transform a string with an object of replacement patterns
replace.strWithObj(String, replacements);
// Transform an array of strings with an object of replacement patterns
replace.arrWithObj(Array,  replacements);

.strWithArr( string, array )

Transform a string with an array of replacement patterns.

Parameters:

  • String: The string to modify with the given replacement patterns.
  • Array: Array of objects containing the replacement patterns, each including a pattern property (which can be a string or a RegExp), and a replacement property (which can be a string or a function to be called for each match).
  • A new string is returned with some or all matches replaced by the given replacement patterns.

Example 1

Given the following:

var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
var patterns = [
  {
    pattern: /[ABC]/g,
    replacement: '###'
  },
  {
    pattern: /[XYZ]/g,
    replacement: '$$$'
  },
  ...
];

replace.strWithArr(str, patterns));
// => #########DEFGHIJKLMNOPQRSTUVW$$$$$$$$$

patterns as arrays

Patterns may also be arrays. When replacement patterns are formatted as arrays Frep will first transform the array into a corresponding RegExp group:

Example 2

['[ABC]', '[XYZ]']

gets converted to:

 /([ABC]|[XYZ])/gi

Example 3

So the following will produce a similar result to Example 1, except ### is used to replace all patterns:

var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
var patterns = [
  {
    pattern: ['[ABC]', '[XYZ]'],
    replacement: '###'
  }
];

replace.strWithArr(str, patterns));
// => #########DEFGHIJKLMNOPQRSTUVW#########

.arrWithArr( array, array )

Transform an array of strings with an array of replacement patterns

Parameters:

  • Array: The string to modify with the given replacement patterns.
  • Array: Same as replacStr, this is an an array of objects containing the replacement patterns, each including a pattern property, which can be a string or a RegExp, and a replacement property, which can be a string or a function to be called for each match.
  • A new array of strings is returned with some or all matches replaced by the given replacement patterns.

Given the following:

Example 4

var arr = [
  'Jon Schlinkert',
  'Brian Woodward'
];

var patterns = [
  {
    pattern: /(B|S)/g,
    replacement: '###'
  },
  {
    pattern: /(J|W)/g,
    replacement: '$$$'
  },
  ...
];

replace.arrWithArr(arr, patterns));
// => ["$$$on ###chlinkert", "###rian $$$oodward"]

An array of new strings is returned, with some or all matches in each string replaced by the given replacement strings.

.strWithObj( string, object )

Transform a string with an object of replacement patterns

Parameters:

  • String: The string to modify with the given replacement patterns.
  • Object: Object of replacement patterns, where each key is a string or a RegExp pattern, and each value is the replacement string or function to be called for each match.
  • A new string is returned with some or all matches replaced by the given replacement patterns.

Example 5

Given the following:

var str = 'ABC'
var replacements = {
  'A': 'AAA',
  'B': 'BBB',
  'C': 'CCC',
  'D': 'DDD',
  'E': 'EEE',
  'F': 'FFF'
};

replace.strWithObj(str, replacements));
// => AAABBBCCC

.arrWithObj( array, object )

Transform an array of strings with an object of replacement patterns

Parameters:

  • Array: The array of strings to modify with the given replacement patterns.
  • Object: Object of replacement patterns, where each key is a string or a RegExp pattern, and each value is the replacement string or function to be called for each match.
  • A new array of strings is returned with some or all matches replaced by the given replacement patterns.

Example 6

Given the following:

var arr = ['ABC', 'DEF'];
var replacements = {
  'A': 'AAA',
  'B': 'BBB',
  'C': 'CCC',
  'D': 'DDD',
  'E': 'EEE',
  'F': 'FFF'
};

replace.arrWithObj(arr, replacements));
// => ['AAABBBCCC', 'DDDEEEFFF']

Usage example

replace.strWithArray( string, array )

Slugify URL segments using frep

To run the example, first do: npm install frep underscore.string

var replace = require('frep');

// We'll use underscore string's slugify function for the first example
var _str = require('underscore.string');

// A custom slugification function for the second
var slugger = function(str) {
  return str.replace(/( |-|\.)/g, '_').toLowerCase();
};

// And a third slugification function for the last example
var sluggifier = function(str) {
  return str.replace(/( |\.)/g, '-');
};

// This is an object of data, where each property will be used
// to build up a URL that needs to be slugified.  e.g.
// => /foo/bar/baz
// (in reality, you would probably have an array of objects like this)
var obj = {
  foo: 'This is foo.',
  bar: 'ThIs iS bAr.',
  baz: 'THIS is BAZ.',
};

// Our custom replacement patterns. These are used to
// transform the data from each property
var patterns = [
  {
    pattern: /:foo/g,
    replacement: _str.slugify(obj.foo) // underscore.string
  },
  {
    pattern: /:bar/g,
    replacement: slugger(obj.bar)  // custom function #1
  },
  {
    pattern: /:baz/g,
    replacement: sluggifier(obj.baz)  // custom function #2
  }
];

// The first argument, a string, will be our "structure",
// which will determine where the values from each property
// will be placed. Run frep to see what happens!
console.log(replace.strWithArr(':foo/:bar/:baz', patterns));

Author

Jon Schlinkert

License

Copyright (c) 2014 Jon Schlinkert, contributors. Released under the MIT license


This file was generated by verb-cli on May 14, 2014.

frep's People

Contributors

jonschlinkert avatar otouto avatar vovayatsyuk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

frep's Issues

Is there any posibility to replace string as is, without regex convertation?

The following rules cause frep to throw an error.

{
    pattern: "<comment><![CDATA[",
    replacement: ""
}

Produce the following error:

Invalid regular expression: /<comment><![CDATA[/: Unterminated character class.

and

{
    "<comment><![CDATA[": ""
}

Produces

Invalid regular expression: /<comment><![CDATA[|patterns/: Unterminated character class.

greedy

Hi,

its a nice lib, but I can't figure out why it doesn't support greedy replacement? Could you please add it?

Kind
Marc

Edit: Ok, I'm stupid, of course I can add greedy to my pattern, like:

{
    pattern: /\[{2}/g,
    replacement: "{{"
},

How to get regexp group content?

Greetings!

If a matching regexp has groups as result, is it possible to get the different groups contents?

Maybe in this case, the replacement as function match variable, could be an array with regexp groups contents.

example text:
random text **(anyword) random text

match: **(anyword)
group1: anyword

pattern: /(?:*{2}()([^)*]+)(?:))/g,
replacement: function(match) {
return '--' + match[0] + '--';
}

result:
random text --anyword-- random text

This would be very great.

Edit:
I realized the match variable cannot be changed, because it would broke the original function, but then it would be good to get back an optional extra array variable with groups and contents.

Different release in the npm registry

frep is nice. Thanks for putting it up.

Is it possible that there is a different release in the npm registry? Looks like that the version there has a missing lodash dependency. It is only declared as a dev dependency in the package.json. So the repo version with the tag 0.1.6 differs from the one which is in the registry.

  "devDependencies": {
    "chai": "~1.9.0",
    "mocha": "~1.17.1",
    "lodash": "~2.4.1",
    "underscore.string": "~2.3.3"
  }

Therefore

Error: Cannot find module 'lodash'

No result at all

Somehow it is me misusing your module, but I can't make it working.
I'm trying to replace some text in a html file, but it doesn't work at all.
Tried multiple times, even with only one letter, I'm pretty sure it's not my regex as I've tested it successfully in regex101.com.

EDIT: I just noticed this output from terminal : Error caught from js-beautify: Object # has no method 'map'. ' Perhaps it's connected with my bug, it only appears when I add Frep task to gulpfile.

gulp v3.5.2

package.json

{
  "name": "css_starter-gulp",
  "version": "0.0.0",
  "description": "gulp build of css_starter",
  "main": "index.js",
  "scripts": {},
  "author": "Vivien Garcia",
  "license": "BSD-2-Clause",
  "devDependencies": {
    "gulp": "~3.5.2",
    "event-stream": "~3.1.0",
    "gulp-util": "~2.2.14",
    "gulp-rename": "~1.0.0",
    "gulp-jade": "~0.4.1",
    "gulp-html-prettify": "0.0.1",
    "gulp-frep": "~0.1.0",
    "gulp-htmlhint": "0.0.7",
    "gulp-jshint": "~1.4.0",
    "gulp-sass": "~0.6.0",
    "gulp-autoprefixer": "0.0.6",
    "gulp-minify-css": "~0.3.0",
    "gulp-bless": "0.0.3",
    "gulp-concat": "~2.1.7",
    "gulp-uglify": "~0.2.1",
    "gulp-notify": "~0.4.5"
  }
}

gulpfile.js

/////////////////////////////////////////////////////////////////////////
// I N C L U D E S
// Include gulp
var gulp = require('gulp');
// Include Our Plugins
var jade = require('gulp-jade'); // templates processing
var html_prettify = require('gulp-html-prettify');
var frep = require('gulp-frep'); // replace external js file name in html head
var jshint = require('gulp-jshint'); // code validation
var sass = require('gulp-sass'); // css processing and formating
var prefix = require('gulp-autoprefixer');
var minifyCSS = require('gulp-minify-css');
var bless = require('gulp-bless');
var concat = require('gulp-concat'); // js formating
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var notify = require("gulp-notify"); // notification using osx native notification center

/////////////////////////////////////////////////////////////////////////
// T A S K S
// Template processing
gulp.task('templates', function() {
    var YOUR_LOCALS = {
        pretty: true
    };
    gulp.src('./_source/**/*.jade')
        .pipe(jade({
          locals: YOUR_LOCALS
        }))
        .pipe(gulp.dest('./_build/stage')) // save minified to stage
        .pipe(html_prettify({
            indent_char: ' ',  indent_size: 4
        }))
        .pipe(gulp.dest('./_build/dev')) // save expanded to dev
        .pipe(notify({ message: 'Templates processed!' }));
});


gulp.task('frep', function() {
    var patterns = {
            pattern: /javascript\.js/,
            replacement: 'javascript.min.js'
    };

    gulp.src('./_build/stage/test.html')
        .pipe(frep(patterns))
        .pipe(rename('tested.html'))
        .pipe(gulp.dest('./_build/stage'));
});

// Code lint
gulp.task('lint', function() {
    gulp.src('./_source/_js/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(notify({ message: 'Javascript hinted!' }));
});

// css processing
gulp.task('processing', function() {
    gulp.src('./_source/_sass/*.scss')
        .pipe(sass({ // preprocessing sass files
        // noCache: true, style: 'expanded', precision: 7, debugInfo: true, lineNumbers: true
        }))
        .pipe(rename('1-preprocessed.css'))
        .pipe(gulp.dest('./_build/dev/__tmp')) // save a copy for step-by-step debugging
        .pipe(prefix())
        .pipe(rename('2-prefixed.css'))
        .pipe(gulp.dest('./_build/dev/__tmp')) // new copy for step-by-step debugging
        .pipe(rename('stylesheet.css'))
        .pipe(bless('stylesheet.css')) // good timing to bless files and prefix
        .pipe(gulp.dest('./_build/dev/_assets/_css')) // saving file to dev
        .pipe(minifyCSS({
            keepSpecialComments: 1, removeEmpty: true
        }))
        .pipe(rename('stylesheet.min.css'))
        .pipe(gulp.dest('./_build/stage/_assets/_css')) // finaly we save for stage
        .pipe(notify({ message: 'CSS Sassified and post-processed!' }));
});

// Concatenate & Minify JS
gulp.task('scripts', function() {
    gulp.src('./_source/_js/*.js')
        .pipe(gulp.dest('./_build/dev/_assets/_js')) // simple copy of js files to dev
        .pipe(concat('all.js')) // concatenation, minification and save to stage
        .pipe(gulp.dest('./_build/dev/__tmp'))
        .pipe(uglify())
        .pipe(rename('javascript.min.js'))
        .pipe(gulp.dest('./_build/stage/_assets/_js'))
        .pipe(notify({ message: 'Javascript post-processed!' }));
});

// Watch files for changes
gulp.task('watch', function() {
    gulp.watch('./_source/_js/*.js', ['lint', 'scripts']);
    gulp.watch('./_source/_sass/*.scss', ['sass']);
});

// Final notification
gulp.task('notification', function() {
    gulp.src('./dev/__tmp')
        .pipe(notify({ message: 'Gulped!' }));
});

/////////////////////////////////////////////////////////////////////////
// D E F A U L T   T A S K
gulp.task('default', ['templates', 'frep', 'lint', 'processing', 'scripts', 'notification']);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.