skip to Main Content

I need to format text based on provided text specific style using react js. e.g:

  1. If text contains this: nBubblenAirnSKY

Output: Bubble<br/>Air<br/>SKY<br/>

  1. If text contains like this: n-Bubblen-Airn-SKY

Output :

  • Bubble

  • Air

  • SKY

Here 1 hyphen (-) = one unordered list

  1. If text contains like this: n#Bubblen#Airn#SKY

Output:
1.Bubble
2.Air
3.SKY

  1. If text contains like this: n-Bubblen–Airn—SKYn—-Cloud

Output:

  • Bubble
    • Air
      • SKY
        • Cloud

In the above text, Each hyphen increase means it should be the child unordered list according to their parent list item.

I need to show the output using html based on text condition

I have seen in XAML textbox (windows) if i add the text with above style text behaves like as shown in output.

What i am tried to find the n and replace with <br/> tag.

var text = "nBubblenAirnSKY"
var newChar = new RegExp(/^[S.]+$/g);
var isNewLineExist = newChar.test(text);
if(isNewLineExist) //this is working fine if string contains newline character
     console.log('newline exist in string');
else
    console.log('newline does not exist in string');

//But below code for replace is not working. Where i tried to replace n with <br/> based on regex

    var replaceChar = text.replace(/^[n.]/g, "<br/>");
    console.log(replaceChar);
    return replaceChar;
//Looking for other output also.

I have tried with other regex then include() but they are not able to find if string contains n character.

Need help

2

Answers


  1. You can create a component in React js for this and you can reuse it.

    import React from 'react';
    
    const formatTextWithLB= ({children}:{children:string}) => {
     
      const formattedText = children.replace(/n/g, '<br/>');
      return { __html: formattedText };
    };
    
    const FormattedText = ({ text }:{text:string}) => {
      return (
        <div dangerouslySetInnerHTML={formatTextWithLB(text)} />
      );
    };
    
    const App = () => {
      const text = "nBubblenAirnSKY";
      
      return (
        <div>
          <h1>Formatted Text:</h1>
          <FormattedText >
         {text}
          </FormattedText>
        </div>
      );
    };
    
    export default App;
    
    Login or Signup to reply.
  2. You might need to handle different cases using regular expressions and conditionally render the HTML. I would do it like following:

    class FormattedText extends React.Component {
      formatText = (text) => {
        if (!text) return '';
    
        // Split the input text into lines
        const lines = text.trim().split('n');
    
        // Define the variables to hold the output
        let result = [];
        let ulStack = [];
        let olStack = [];
    
        lines.forEach((line) => {
          if (line.startsWith('-')) {
            // Handle unordered lists
            const level = line.match(/-/g).length;
            const content = line.replace(/^-+/, '').trim();
    
            while (ulStack.length >= level) {
              result.push('</ul>');
              ulStack.pop();
            }
    
            if (ulStack.length < level) {
              result.push('<ul>');
              ulStack.push(level);
            }
    
            result.push(`<li>${content}</li>`);
          } else if (line.startsWith('#')) {
            // Handle ordered lists
            const level = line.match(/#/g).length;
            const content = line.replace(/^#+/, '').trim();
    
            while (olStack.length >= level) {
              result.push('</ol>');
              olStack.pop();
            }
    
            if (olStack.length < level) {
              result.push('<ol>');
              olStack.push(level);
            }
    
            result.push(`<li>${content}</li>`);
          } else {
            // Handle plain text with <br/> tags
            result.push(`${line}<br/>`);
          }
        });
    
        while (ulStack.length > 0) {
          result.push('</ul>');
          ulStack.pop();
        }
    
        while (olStack.length > 0) {
          result.push('</ol>');
          olStack.pop();
        }
    
        return result.join('');
      };
    
      render() {
        const { text } = this.props;
        return (
          <div dangerouslySetInnerHTML={{ __html: this.formatText(text) }} />
        );
      }
    }
    
    class App extends React.Component {
      render() {
        const exampleText1 = 'nBubblenAirnSKY';
        const exampleText2 = 'n-Bubblen-Airn-SKY';
        const exampleText3 = 'n#Bubblen#Airn#SKY';
        const exampleText4 = 'n-Bubblen--Airn---SKYn----Cloud';
    
        return (
          <div>
            <h2>Example 1:</h2>
            <FormattedText text={exampleText1} />
    
            <h2>Example 2:</h2>
            <FormattedText text={exampleText2} />
    
            <h2>Example 3:</h2>
            <FormattedText text={exampleText3} />
    
            <h2>Example 4:</h2>
            <FormattedText text={exampleText4} />
          </div>
        );
      }
    }
    
    
    ReactDOM.render(
      <App/>,
      document.getElementById("root")
    );
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

    So, here FormattedText component uses dangerouslySetInnerHTML to display the HTML components.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search