Transform text to html based on regex and show it in input or ContentEditable

40 Views Asked by At

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

1

There are 1 best solutions below

1
root_coding On BEST ANSWER

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

import React, { useState } from "react";
import ReactDOM from "react-dom/client";

function CreateTemplate() {
  const [content, setContent] = useState("");

  const handleInputChange = (e) => {
    const newText = e.target.textContent;
    const formattedText = newText.replace(
      /\(\$(.*?)\)/g,
      (_, variable) => `<span class="variable">${variable}</span>`
    );
    setContent(formattedText);
  };

  return (
    <div contentEditable onInput={handleInputChange}>
      {content && (
        <div>
          <h2>Formatted Output:</h2>
          <div dangerouslySetInnerHTML={{ __html: content }} />
        </div>
      )}
    </div>
  );
}

function App() {
  return (
    <div>
      <h1>Variable Formatter</h1>
      <CreateTemplate />
    </div>
  );
}

const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(<App/>);