如何将bbcode字符转换为jsx? (丰富文字) [英] How can I convert bbcode characters to jsx? (enriching text)

查看:128
本文介绍了如何将bbcode字符转换为jsx? (丰富文字)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文本=我有此文本[b],并且希望此部分为粗体[/b]."

如何用 strong html标签替换[b][/b]

以使输出为=>我有此文本,并希望此部分为粗体.

我尝试像这样使用lodash替换,但是eslint抱怨结束标记:

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

mcve

解决方案

应该使用现有的库来实现此目的,而不是使用基本的替换.如果构建自制解决方案,则将以另一个库的较差版本结束.在这里,我将使用我最喜欢的搜索引擎上"react bbcode"顶部的库.好的,我们运行 bbcode-to-react .他们甚至有一个例子.让我们将其粘贴到您的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;

输出:

foo bar

好的.您可以在repl.it上进行尝试: https://repl.it/repls/SeagreenDarkcyanNumerator

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

这篇关于如何将bbcode字符转换为jsx? (丰富文字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆