How to implement find and replace functions? #5937
-
For example, I want to highlight all the "AAA" in the editor, or replace all the "AAA" in the editor with "BBB". Is there any available code or method? thanks |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
I would use COMMAND if that function is fired on event like button click. here is a simple implementation. 2024-04-22.6.36.13.movimport type {LexicalCommand, LexicalEditor} from 'lexical';
import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
import {
$nodesOfType,
COMMAND_PRIORITY_EDITOR,
createCommand,
TextNode,
} from 'lexical';
import React, {useEffect} from 'react';
interface Payload {
from: string;
to: string;
}
const FIND_REPLACE_COMMAND: LexicalCommand<Payload> = createCommand(
'FIND_REPLACE_COMMAND',
);
const listener = ({from, to}: Payload, editor: LexicalEditor) => {
editor.update(() => {
const textNodes = $nodesOfType(TextNode);
for (const node of textNodes) {
const text = node.getTextContent();
node.setTextContent(text.replaceAll(from, to));
}
});
return true;
};
export default function FindReplacePlugin() {
const [editor] = useLexicalComposerContext();
useEffect(() => {
return editor.registerCommand(
FIND_REPLACE_COMMAND,
listener,
COMMAND_PRIORITY_EDITOR,
);
}, [editor]);
return (
<button
onClick={() => {
editor.dispatchCommand(FIND_REPLACE_COMMAND, {from: 'aaa', to: 'bbb'});
}}>
aaa to bbb
</button>
);
} I think you could tweak from here or find better approach. |
Beta Was this translation helpful? Give feedback.
-
If you want to replace browser's default finder with lexical's, They use |
Beta Was this translation helpful? Give feedback.
-
@2wheeh Thank you |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
I would use COMMAND if that function is fired on event like button click.
here is a simple implementation.
2024-04-22.6.36.13.mov