Replace part of string with tag in JSX

前端 未结 12 1235
被撕碎了的回忆
被撕碎了的回忆 2020-12-16 09:39

I\'m trying to replace parts of a string with JSX tags, like so:

render: function() {
    result = this.props.text.replace(\":\",
相关标签:
12条回答
  • 2020-12-16 10:20

    The accepted answer is two years old. For this problem issue #3368 was created and based on the solution provided by a Facebook employee working on React, react-string-replace was created.

    Using react-string-replace, here is how you can solve your problem

    const reactStringReplace = require('react-string-replace');
    
    const HighlightNumbers = React.createClass({
      render() {
        const content = 'Hey my number is 555:555:5555.';
        return (
          <span>
            {reactStringReplace(content, ':', (match, i) => (
              <div className="spacer"></div>
            ))}
          </span>
        );
      },
    });
    
    0 讨论(0)
  • 2020-12-16 10:21

    After some research I found that existing libraries doesn't fit my requirements. So, of course, I have written my own:

    https://github.com/EfogDev/react-process-string

    It is very easy to use. Your case example:

    let result = processString({
        regex: /:/gim,
        fn: () => <div className="spacer"></div>
    })(this.props.test);
    
    0 讨论(0)
  • 2020-12-16 10:21

    I had the more common task - wrap all (English) words by custom tag. My solution:

    class WrapWords extends React.Component {
      render() {
        const text = this.props.text;
        const isEnglishWord = /\b([-'a-z]+)\b/ig;
        const CustomWordTag = 'word';
    
        const byWords = text.split(isEnglishWord);
    
        return (
        <div>
          {
            byWords.map(word => {
              if (word.match(isEnglishWord)) {
                return <CustomWordTag>{word}</CustomWordTag>;
              }
              return word;
            })
          }
        </div>
        );
        
      }
    }
    
    // Render it
    ReactDOM.render(
      <WrapWords text="Argentina, were playing: England in the quarter-finals (the 1986 World Cup in Mexico). In the 52nd minute the Argentinian captain, Diego Maradona, scored a goal." />,
      document.getElementById("react")
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    
    <div id="react"></div>

    0 讨论(0)
  • 2020-12-16 10:22

    Wrote a utility function for jsx.

    const wrapTags = (text: string, regex: RegExp, className?: string) => {
      const textArray = text.split(regex);
      return textArray.map(str => {
        if (regex.test(str)) {
          return <span className={className}>{str}</span>;
        }
        return str;
      });
    };
    
    
    0 讨论(0)
  • 2020-12-16 10:22

    If you'd also like to be able to make replacements within replacements (for example, to highlight search terms within urls), check out this node module I created - https://github.com/marcellosachs/react-string-replace-recursively

    0 讨论(0)
  • 2020-12-16 10:23

    You guys are using complicated approaches, Just keep it simple:

    function replaceJSX(str, find, replace) {
        let parts = str.split(find);
        for(let i = 0, result = []; i < parts.length; i++) {
            result.push(parts[i]);
            result.push(replace);
        }
        return (
            <>{result}</>
        );
    }
    

    Usage

    replaceJSX(variable, ":", <br />);
    
    0 讨论(0)
提交回复
热议问题