Replace part of string with tag in JSX

前端 未结 12 1284
被撕碎了的回忆
被撕碎了的回忆 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 09:57

    I have come to following simple solution that does not include third party library or regex, maybe it can still help someone.

    Mainly just use .replace() to replace string with regular html written as string, like:

    text.replace('string-to-replace', '')
    

    And then render it using dangerouslySetInnerHTML inside an element.

    Full example:

    const textToRepace = 'Insert :' // we will replace : with div spacer
    const content = textToRepace.replace(':', '
    ') : '' // then in rendering just use dangerouslySetInnerHTML render() { return(
    ) }

提交回复
热议问题