I'm trying to write a simple text replacer in React.js using a regular expression but I can't wrap my head around it.
So I've got a list of tokens and their corresponding replacement text. I also have a text area with text written by the user. Whenever a word is wrapped around { } the text will be replaced with the replacement text of the corresponding token.
For example if I have a {example} somewhere in my textarea I will have to check my tokenlist and see if I have the value example in the list and replace {example} with the value of the replacement value of the list.
What I'm doing right now is to check if I have any matches in my textarea using:
let regEx = /\{[a-zA-Z_][a-zA-Z0-9_]*\}/;
inputText.match(regEx);
As a result I'm getting an index and the input but how can I replace the matched text with the replacement text? I tried using the replace function but somehow I couldn't understand how to use it.
Here is my filter function for you to check out:
this.filterText = () => {
//check if we have text in Input text area
if (this.state.inputText) {
let regEx = /\{[a-zA-Z_][a-zA-Z0-9_]*\}/;
let inputText = this.state.inputText;
this.state.data.forEach((token, index) => {
let match = inputText.match(regEx);
if (match) {
console.log('match:', match);
//should replace matched text with replacement text
inputText.replace(regEx, this.state.data[index].replacementText);
}
});
}
}