Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace strings to tag in react

I am trying to replace :: and ;; to

const text = 'Welcome :: my ;;'.replace('::', <Strong>to</Strong>).replace(';;', <Strong>world</Strong>);

I am getting this Welcome [object Object] my [object Object].

Expected response Welcome **to** my **world**.

Can anyone please help me on that.


Updated question

There will be random text like this:

  1. Welcome :: my ;;
  2. Welcome ;; my ::
  3. Hello ::

And replace :: with dynamic value suppose to only and ;; with dynamic value world only.

like image 499
Dhaval Parmar Avatar asked May 04 '26 07:05

Dhaval Parmar


1 Answers

JSX elements are syntax sugar for React DOM elements, which are objects. A string on it's own won't carry information about things such as font size or weight, so it may be best to represent the whole thing by JSX. I think something along these lines would do it:

const text = 'Welcome :: my ;;';
const myWorld = (
  <span>
    {text.split(' ').map((word, index) => {
      const space = index == 0 ? '' : ' ';
      if (word == '::') {
        return (<strong key={index}>{space + "to"}</strong>);
      } else if (word == ';;') {
        return (<strong key={index}>{space + "world"}</strong>);
      }

      return (<span key={index}>{space + word}</span>);
    }}
  </span>
);

If you need the replacements to be dynamic, you can create a function for this:

// Example `replacements` object:
// { 
//   '::': 'to',
//   ';;': 'world',
// }

function replaceWithEmphasis(text, replacements) {
  const words = text.split(' ');
  
  return (
    <span> 
      {
        words.map((word, index) => {
          const replaced = replacements[word];

          // Preserve spaces between words
          const space = index == 0 ? '' : ' ';

          if (replaced != null) {
            return <strong key={index}>{space + replaced}</strong>;
          } else {
            return <span key={index}>{space + word}</span>;
          }
        })
      }
    </span>
  );
}
like image 112
Michael Horn Avatar answered May 06 '26 20:05

Michael Horn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!