How can I convert bbcode characters to jsx? (enriching text)

馋奶兔 提交于 2020-03-05 03:04:37

问题


Text = "I have this text [b] and want this part to be bold [/b]."

How can I replace the [b] and [/b] with strong html tag

so that the output is => I have this text and want this part to be bold.

I tried using lodash replace like this but eslint is complaining for the closing tag:

let startTag = _.replace(text, '[b]', <strong>);
let endTag= _.replace(startTag, '[/b]', </strong>);

mcve


回答1:


Instead of using a basic replace, you should rely on an existing library to achieve this. If you build an homemade solution, you will end with a poor version of another library. Here I will use the library at the top of "react bbcode" on my favorite search engine. Ok lets run bbcode-to-react. They even have an example. Lets copy paste it to your mcve.

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import parser from 'bbcode-to-react';

class App extends Component {
  render() {
    return (
      <p>{parser.toReact('foo [b]bar[/b]')}</p>
    );
  }
}

export default App;

ouput:

foo bar

Alright. You can try it on repl.it: https://repl.it/repls/SeagreenDarkcyanNumerator



来源:https://stackoverflow.com/questions/59629664/how-can-i-convert-bbcode-characters-to-jsx-enriching-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!