0

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

aloisdg
  • 22,270
  • 6
  • 85
  • 105
  • you example is not valid; that's probably why eslint is complaining. – Dan O Jan 07 '20 at 14:00
  • It could be fix with `dangerouslySetInnerHTML` (read https://stackoverflow.com/questions/23616226/insert-html-with-react-variable-statements-jsx). But since you are looking to parse BBCode, use a bbcode parser. – aloisdg Jan 07 '20 at 14:03

1 Answers1

0

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

aloisdg
  • 22,270
  • 6
  • 85
  • 105
  • By the way if there is a better solution I would love to read it. This one fix the problem as expected, but it could be better. A better solution could take the form of a buildin mode of react use to handle BBCode markup (a premade component for example). – aloisdg Jan 07 '20 at 15:40