You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何从Jodit Editor提取纯文本而非HTML输出?

在React的Jodit Editor中提取纯文本内容

方法一:使用Jodit内置的getText()方法(推荐)

Jodit编辑器本身提供了获取纯文本的API,无需手动解析HTML,直接通过编辑器实例调用getText()即可拿到纯文本内容。

修改后的组件代码如下:

import { Button, Input } from "@chakra-ui/react";
import React, { useRef, useState } from "react";
import JoditEditor from "jodit-react";

function Qinp(props) {
  const [inp, setinp] = useState("");
  const [plainText, setPlainText] = useState("");
  const editor = useRef(null);

  // 点击按钮提取纯文本
  const extractPlainText = () => {
    if (editor.current) {
      const text = editor.current.editor.getText();
      setPlainText(text);
      // 若需要同步到inp状态,取消下面注释
      // setinp(text);
    }
  };

  // 可选:实时监听编辑器内容变化,自动同步纯文本
  const handleEditorChange = () => {
    if (editor.current) {
      const text = editor.current.editor.getText();
      setPlainText(text);
    }
  };

  return (
    <div>
      <JoditEditor 
        ref={editor} 
        onChange={handleEditorChange} // 开启实时同步则保留此属性
      />
      <Button onClick={extractPlainText} mt={4}>提取纯文本</Button>
      <Input 
        mt={4} 
        value={plainText} 
        placeholder="提取后的纯文本" 
        readOnly 
      />
    </div>
  );
}
export default Qinp;

方法二:手动解析HTML为纯文本

如果不想依赖编辑器内置方法,可以通过创建临时DOM元素解析HTML内容:

import { Button, Input } from "@chakra-ui/react";
import React, { useRef, useState } from "react";
import JoditEditor from "jodit-react";

function Qinp(props) {
  const [inp, setinp] = useState("");
  const [plainText, setPlainText] = useState("");
  const editor = useRef(null);

  // HTML转纯文本的辅助函数
  const htmlToPlainText = (html) => {
    const tempElement = document.createElement("div");
    tempElement.innerHTML = html;
    return tempElement.textContent || tempElement.innerText || "";
  };

  const extractPlainText = () => {
    if (editor.current) {
      // 获取编辑器的HTML内容
      const htmlContent = editor.current.editor.getValue();
      const text = htmlToPlainText(htmlContent);
      setPlainText(text);
    }
  };

  return (
    <div>
      <JoditEditor ref={editor} />
      <Button onClick={extractPlainText} mt={4}>提取纯文本</Button>
      <Input 
        mt={4} 
        value={plainText} 
        placeholder="提取后的纯文本" 
        readOnly 
      />
    </div>
  );
}
export default Qinp;

注意:手动解析的方式可能无法处理编辑器中的特殊格式或自定义内容,优先使用官方提供的getText()方法。

内容的提问来源于stack exchange,提问作者Pradeep L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 11:50:24