Description
Thanks for a very cool function! What I'm trying to do is replace a user selected string in a body of text with a React component (that contains the selected string). The issue I'm running into is that react-string-replace is replacing all instances of a selection, rather than just the first match.
Since I'm targeting user-selected text (via the Selection API), I'm using a RegExp constructor, like so:
const key = uuid(); // generate unique key
const textRegex = new RegExp(`(${window.getSelection().toString()})`); // capture user selection
const updatedText = ReactStringReplace(postText, textRegex, match => {
return <HighlightSpan text={match} key={key} />; // return React component
});
// other stuff
This works absolutely perfectly if the selected string is unique in the body of text, but if there is another match then I run into a duplicate key error (and also highlight multiple selections when I only want the first).
Since the RegExp constructor doesn't include a 'g' flag, as far as I understand it should only match the first occurrence - but I might be mistaken as to how react-string-replace works! Is it possible to have it run only once, and if so could you please give me a tip on how to achieve this?
Thanks in advance,
Jake
EDIT
Just actually checked the code and realized that the g & i flags are set by default - perhaps I could make a pull request to have the regex flags optional?