We have to select text from the Gutenberg editor. The purpose is to store and replace text. Please use this code to help us with you
const { select } = wp.data;
const selectedBlock = select('core/block-editor').getSelectedBlock();
if (selectedBlock) {
const selectedText = selectedBlock.attributes.content;
console.log("Selected Text:", selectedText);
// Store the selectedText as needed.
}
Replacing Text within a Block
const { dispatch } = wp.data;
const newText = "New Text to Replace";
dispatch('core/block-editor').updateBlockAttributes(selectedBlock.clientId, {
content: newText
});
I am saving and Reusing Selected Text using the console.log()
localStorage.setItem('selectedText', selectedText);
const storedText = localStorage.getItem('selectedText');
console.log("Stored Text:", storedText);
const { registerPlugin } = wp.plugins;
const { PluginBlockSettingsMenuItem } = wp.editPost;
const MyReplaceTextPlugin = () => (
<PluginBlockSettingsMenuItem
label="Replace Text"
onClick={() => {
const newText = "Replaced Text!";
dispatch('core/block-editor').updateBlockAttributes(selectedBlock.clientId, {
content: newText
});
}}
/>
);
registerPlugin('my-replace-text-plugin', {
render: MyReplaceTextPlugin
});