将字符串替换为反应中的标记

Replace strings to tag in react

我正在尝试替换 :: 和 ;;至

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

我明白了 Welcome [object Object] my [object Object].

预期响应 Welcome **to** my **world**.

谁能帮我解决这个问题。


更新问题

会有这样的随机文字:

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

并用动态值替换 ::,假设仅 to;; 仅用动态值 world

你可以这样做

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

然后使用 dangerouslySetInnerHTML

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

JSX 元素是 React DOM 元素的语法糖,它们是对象。一个字符串本身不会携带诸如字体大小或粗细之类的信息,因此最好用 JSX 来表示整个内容。我认为按照这些思路可以做到这一点:

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>
);

如果您需要动态替换,您可以为此创建一个函数:

// 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>
  );
}