Successfully added
React
by Patrik
TinyMCE: How to Remove All data-* Attributes with a Custom Button
If you're using TinyMCE in a React app and want to provide users with a way to remove all data-*
attributes from their content, you can create a custom toolbar button to do just that.
Why do this?
data-*
attributes are often added by frameworks, plugins, or tracking tools. In some cases, you might want to remove these before saving or publishing content, especially for clean, production-ready HTML.
How to Add the Button
You can use TinyMCE’s setup
function to add a custom button with a mop-like icon to your toolbar. Here's how:
import { Editor } from '@tinymce/tinymce-react';
function MyEditor({ content, contentChange, onEditorInit }) {
return (
<Editor
value={content}
onEditorChange={(newValue) => contentChange(newValue)}
onInit={onEditorInit}
init={{
height: 500,
menubar: false,
plugins: 'code',
toolbar: 'undo redo | mopCleaner | bold italic underline | code',
setup: (editor) => {
editor.ui.registry.addIcon('mopCleanerIcon', `
<svg width="24" height="24" viewBox="0 0 24 24">
<path d="M12 2v14" stroke="currentColor" stroke-width="2"/>
<path d="M8 16h8l1 4H7l1-4z" fill="currentColor"/>
</svg>
`);
editor.ui.registry.addButton('mopCleaner', {
icon: 'mopCleanerIcon',
tooltip: 'Remove all data-* attributes',
onAction: () => {
const currentContent = editor.getContent();
const cleanedContent = currentContent.replace(/\sdata-[\w-]+="[^"]*"/g, '');
editor.setContent(cleanedContent);
},
});
},
}}
/>
);
}
How it works:
- The button removes all HTML attributes that match the pattern
data-something="value"
. - It works even when multiple
data-*
attributes are in a single tag. - You can customize the icon or tooltip to match your app's style.
Tip:
To support edge cases, such as attributes with single quotes or no values, you can enhance the regex as needed.
tinymce
react
contenteditor
html
customization
Referenced in:
Comments