简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM