Git Product home page Git Product logo

regexify-string's Introduction

npm bundle size GitHub release (latest by date) npm-donwloads-per-year


regexify-string

Strings decorator (by regex) with: React components, HTML tags etc.

perfectly works with: strings, html tags, react, react-native

Install

$ npm install --save regexify-string

or

$ yarn add regexify-string

API

regexifyString({ pattern, decorator, input })

pattern

Type: RegExp

decorator

Type: (match: string, index: number, result?: RegExpExecArray) => string | JSX.Element

  • match string you would like to replace/decorate with something
  • index index number of the current match
  • result? RegExpExecArray

NOTE: Try do not forget to use keys for React collections if needed

input

Type: string

Usage

with strings

    const result = regexifyString({
        pattern: /\[.*?\]/gim,
        decorator: (match, index) => {
            return `<${match}>`;
        },
        input: 'some [text] with simple example',
    });

    console.log(result);
    // ['some ', '<[text]>', ' with simple example']

with index keys

    const result = regexifyString({
        pattern: /\[.*?\]/gim,
        decorator: (match, index) => {
            switch (index) {
                case 0: return `<FIRST ${match}>`;
                case 1: return `<SECOND ${match}>`;
                case 2: return `<THIRD ${match}>`;
                default: return match;
            }
        },
        input: 'Important text with [first link] and [second link] and much more [links]',
    });

    console.log(result);
    /*
        [
            'Important text with ',
            '<FIRST [first link]>',
            ' and ',
            '<SECOND [second link]>',
            ' and much more ',
            '<THIRD [links]>',
        ]
    */

with html

    const result = regexifyString({
        pattern: /\[.*?\]/gim,
        decorator: (match, index) => {
            return <span>{match}</span>;
        },
        input: 'some [text] with simple example',
    });

    console.log(result);
    // ['some ', <span>[text]</span>, ' with simple example']

with React / React Native components

    regexifyString({
        pattern: /\[.*?\]/gim,
        decorator: (match, index) => {
            return (
                <Link
                    to={SOME_ROUTE}
                    onClick={onClick}
                >
                    {match}
                </Link>
            );
        },
        input: someVariablWithData,
    });
    regexifyString({
        pattern: /\[.*?\]/gim,
        decorator: (match, index) => {
            return <React.Fragment>{match}</React.Fragment>;
        },
        input: 'some [text] with simple example',
    });

with groups

    const result = regexifyString({
        pattern: /\[(?<id>.+)\]\{(?<name>.+)\}/g,
        decorator: (match, index, result) => {
            return (
                <div
                    id={String(result?.[2])}
                    title={result?.[1]}
                />
            );
        },
        input: 'a[b]{c}',
    });

    console.log(result);
    // ['a', <div id='c' title='b' />]

License

MIT © Kas Elvirov

regexify-string's People

Contributors

dependabot[bot] avatar kas-elvirov avatar

Stargazers

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

Watchers

 avatar

regexify-string's Issues

regexifString crash at some scenarios

In some scenarios, the regexifString crashes the browser.
ex:

console.log(

    "regexifyString test",
    regexifyString({
      pattern: /.*/gim,
      decorator: (match, index) => {return 'ReplaceMe';},
      input: "This is a test",
    })

 );

I did a simple debug in the function implementation and found if (match === "") break inside the

while (result !== null) {

    const matchStartAt = result.index;
    const match = result[0];
   ...

}

solve the issue. Can you please consider including this fix?

TypeError: processedInput.substring is not a function

hi
i used couple of patterns for 1 text and I got an error
how can I use this multiple time ?

const content1 = regexifyString({
    pattern: bold_regex,
    decorator: (match, index) => {
      return (
        <span key={index} style={{fontWeight: 'bold'}}>
          ${match}
        </span>
      );
    },
    input: content
  });
const content2 = regexifyString({
    pattern: bold_regex,
    decorator: (match, index) => {
      return (
        <span key={index} style={{fontWeight: 'bold'}}>
          ${match}
        </span>
      );
    },
    input: content1
  });

Matching groups?

I couldn't find a way to match groups. For example:

regexifyString({
    pattern: /\[(?<id>.+)\]\{(?<name>.+)\}/g,
    decorator: (id, name) => (<item b={id} c={name} />),
    input: 'a[b]{c}',
})

// to output:
// [ 'a', <item b='b' c='c' />, '']

Is this possible?

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.