react-string-replace icon indicating copy to clipboard operation
react-string-replace copied to clipboard

Support for running a callback for non-matches

Open pintocarlos opened this issue 8 years ago • 7 comments

A 4th parameter as callback to process non-match items would be useful.

For instance, in ReactNative, plain text cannot be outside of <Text> components. The non matches need to be wrapped in a component as well. A callback for these would come quite handy.

Example:

const matchCallback = (match, i) => (<Text key={i} style={styles.highlight}>{match}</Text>);
const nonMatchCallback = (nonmatch, i) => (<Text key={i}>{nonmatch}</Text>);
const components = reactStringReplace(input, regex, matchCallback, nonMatchCallback);

pintocarlos avatar Aug 02 '17 16:08 pintocarlos

Ah good point, I like this idea. I think it deserves a bit of thought though. One issue would be that this would mean we can't do #6. Another potential issue is that this sort of API seems pretty uncommon (have any examples of libraries that do something similar?).

I'm fully onboard with being able to control non-match output. However, a fourth arg would work but it feels like a quick fix rather than a considered solution. Interested to know what you think @pintocarlos

iansinnott avatar Aug 02 '17 20:08 iansinnott

Thanks for the reply @iansinnott Regarding the use for the API, it is entirely subjective. My example posted above is a valid real world example. In general, I can think of general styling purposes where you'd like to style the non-matches in some way and the matches in another way instead of running the input through reactStringReplace twice with an inverse regex of the first pass through.

With regards to #6, could it coexist with this issue by using a negative lookahead of the input regex? Meaning, the negative regex of the input would return the non-matches.

Now about the 4th param callback for non-matches, it seemed to me the most natural place to put this callback, but I am open to other suggestions that could also work well.

pintocarlos avatar Aug 02 '17 20:08 pintocarlos

What about just adding a second function to this library? The concept of collecting results based on both outcomes of a predicate reminds me of a partition function. Maybe something like stringPartition which would take args:

stringPartition(input, regex, match, nonMatch)

This way it's not a breaking change and doesn't overload the functionality of the replace function any more.

iansinnott avatar Aug 02 '17 20:08 iansinnott

I see your point. Makes sense. reactStringPartition(input, regex, match, nonMatch) ?

pintocarlos avatar Aug 02 '17 21:08 pintocarlos

Yeah, that's what I'm thinking

iansinnott avatar Aug 02 '17 21:08 iansinnott

any updates on this guys?

ghost avatar Dec 09 '20 06:12 ghost

any updates on this guys?

Nope, but I'd be happy to merge a PR if anyone wants to open one.

iansinnott avatar Dec 09 '20 06:12 iansinnott