## plugins – How to hande “image_send_to_editor” hook in between Visual and text

Question

I am using “image_send_to_editor” hook to add attributes in images.
My attributes are : data-align="center" data-attachemet-id="50"
Below is a snippet of code, which is working fine.

add_filter( 'image_send_to_editor',
function( $html,$id, $caption,$title, align,url, $size,$alt )
{
if( $id > 0 ) { if(!$caption || empty($caption)) {$data.= " data-align='".align."' " ;data.=" data-attachemet-id='50' ";
$html = str_replace( "<img src", "<img{$data}src", $html ); }else{$data.= " data-align='".align."' " ;data.=" data-attachemet-id='50' ";
$html = str_replace( '<img'.$data.'src', '<img treyway', $html ); }} return$html;
}, 10, 8 );


I am only adding custom attributes if the media has no caption, while it’s working fine, but if I add the caption to that particular media I am not able to remove those attributes. As I have mentioned that if the image has no caption then only add the attributes but if I add the caption to the same image I want to remove the earlier added attribute.
I am sharing the text of the media below.

1. If the image has no caption

img class="wp-image-19 size-medium" src="http://192.168.1.3/wordpres/wp-content/wp-content/uploads/2021/06/photo-1606788168886-286b0336272d-200x300.jpg" alt="" width="200" height="300" data-align="center" data-attachemet-id="50" />

1. If the same image has updated with the caption then I would like to get the same image without the above added attribute but i am getting those attribute,

 < class="wp-image-19 size-medium" src="http://192.168.1.3/wordpres/wp-content/wp-content/uploads/2021/06/photo-1606788168886-286b0336272d-200x300.jpg" alt="" width="200" height="300" data-align="center" data-attachemet-id="50" /> test 

as you can see that i wants to remove data-align="center" data-attachemet-id="50" attribute if the image has caption.
but I am getting attributes after adding the caption.

Please let me if there is any solution to solve this issue.
I believe there is something that we can do with WordPress Js this is just my opinion.