Home > Software engineering >  Replace strings to tag in react
Replace strings to tag in react

Time:05-28

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.

CodePudding user response:

You can do it like this

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

and then display it using dangerouslySetInnerHTML

render() {
    return (
      <div dangerouslySetInnerHTML={{ __html: text  }} />
    );
  }

CodePudding user response:

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) => {
      if (word == '::') {
        return (<strong key={index}>to</strong>);
      } else if (word == ';;') {
        return (<strong key={index}>world</strong>);
      }

      return (<span key={index}>{word}</span>);
    }}
  </span>
);
  • Related