问题
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