draft-jsで入力されているテキストを取得する

2022年8月26日金曜日

draft-js

t f B! P L

enter image description here

draft-jsは、JavaScirptでリッチテキストエディタの実装をする非常にカスタマイズ性の高いフレームワークである。しかしながら、日本語の情報が少ないため、ちょっとした事でも調べるのに時間がかかることがある。

今回は、エディタ上で入力されているテキストを取得する方法を紹介する。

スポンサーリンク

はじめに

とりあえず動作確認用に、draft-jsのエディタを配置したコンポーネントを作っておく。

import { useState } from 'react';
import { Editor, EditorState } from 'draft-js';
import 'draft-js/dist/Draft.css';

function SampleEditor() {
  const [editorState, setEditorState] = useState(
    () => EditorState.createEmpty(),
  );
  
  return (
    <>
      <Editor
        editorState={editorState}
        onChange={setEditorState}
        customStyleMap={customStyleMap}
      />
    </>
  );
}

export default SampleEditor;

テキスト全文を取得(一番簡単)

単純に、エディタに入力されたテキストを取得するなら、ContentState#getPlainText() で取得するのが一番簡単な方法だ。

editorState.getCurrentContent().getPlainText()
入力値 実行結果
テキスト1
テキスト2
テキスト3
テキスト1
テキスト2
テキスト3

区切り文字を指定する

区切り文字を引数に指定すると、エディタ上の改行を指定した区切り文字にして取得できる。
例えば、getPlainText の引数に , を渡せば、カンマ区切りで各行のテキストが取得できる。

editorState.getCurrentContent().getPlainText(",")
入力値 実行結果
テキスト1
テキスト2
テキスト3
テキスト1,テキスト2,テキスト3

ブロック単位に取得

ブロック単位(改行単位)にテキストを取得する場合は、ContentState#getBlocksAsArray() 関数で取得する。

var text = editorState.getCurrentContent().getBlocksAsArray();
text.map((item) => {
  console.log(item.getText());
});
入力値 実行結果
テキスト1
テキスト2
テキスト3
0:テキスト1
1:テキスト2
2:テキスト3

スポンサーリンク

1文字単位に取得

1文字ずつ、エディタに入力された文字を取得し、その文字に適用されているインラインスタイルも一緒に取得する方法も紹介します。

var blocks = editorState.getCurrentContent().getBlocksAsArray();
blocks.map(block => {
  const text = block.getText();
  block.getCharacterList().map((metadate, index) => {
    const char = text.substr(Number(index), 1);
    //対象の1文字に適用されているインラインスタイルを取得(カンマ区切り)
    const inlineStyles = metadate?.getStyle().join(",");
    //対象の1文字とインラインスタイルを出力
    console.log(char + "(" + inlineStyles + ")");
  })
});

■エディタへの入力内容

enter image description here

■実行結果

d(BOLD)
r(BOLD)
a(BOLD)
f(BOLD)
t(BOLD)
-(BOLD)
j(BOLD)
s(BOLD)
で()
開(red,BOLD)
発(red,BOLD)
!(red,BOLD)
スポンサーリンク
スポンサーリンク

このブログを検索

Profile

自分の写真
Webアプリエンジニア。 日々新しい技術を追い求めてブログでアウトプットしています。
プロフィール画像は、猫村ゆゆこ様に書いてもらいました。

仕事募集もしていたり、していなかったり。

QooQ