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

Answers:

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.