iansinnott / react-string-replace

A simple way to safely do string replacement with React components
MIT License
652 stars 56 forks source link

Support for running a callback for non-matches #23

Open pintocarlos opened 7 years ago

pintocarlos commented 7 years ago

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);
iansinnott commented 7 years ago

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

pintocarlos commented 7 years ago

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.

iansinnott commented 7 years ago

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.

pintocarlos commented 7 years ago

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

iansinnott commented 7 years ago

Yeah, that's what I'm thinking

ghost commented 3 years ago

any updates on this guys?

iansinnott commented 3 years ago

any updates on this guys?

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