I’m currently working on implementing a feature in my React.js project where I want to transform specific patterns from the text typed by user, like ($anyText), into a formatted structure like anyText. This will allow the entered text to be treated as a variable when sent to the backend. I also plan to predefine the variable names for users.
Here is an example of what I’m aiming for: example for what i trying to create
Any suggestions or guidance on how I can achieve this elegantly within the React would be greatly appreciated.
I tried
function CreateTemplate() {
const [content, setContent] = useState("");
const handleInputChange = (e) => {
const newText = e.target.textContent;
const formattedText = newText.replace(
/($(.*?))/g,
'<span class="variable">$1</span>'
);
setContent(formattedText);
};
return <div
contentEditable
onInput={handleInputChange}
dangerouslySetInnerHTML={{ __html: content }}
/>
}
but this is not working as intended at all
2
Answers
I really done my best to know your problem and it gives the output as you required .
please check it’s satisfied your need or not.
Use the below code , I have tested it’s working fine.
This is sample input : This is a sample sentence with variables: ($testing), ($anyText), ($userInput).
NOte: Your code is pointing to wards capturing the variables inside () so make sure it’s right and if you also want to include without () like $userInput then please consider changing regex accordingly
If you are really in a hurry, you can try to access chatgtp, because I took the same approach when encountering similar problems and was able to get a solution.