1

The JavaScript function below is part of a MCEditor WYSIWYG Editor plugin for WordPress.

It searches the post text editor for images in this format:

<p><img src="http://test.dev/primary.jpg" class="mceItem code_syntax_highlighter" data-sh-attr="%20type%3D%22primary%22%20header%3D%22header-text%22%20footer%3D%22footer-text%22" data-sh-content="code-here" data-mce-resize="false" data-mce-placeholder="1" data-mce-src="http://test.dev/primary.jpg"></p>

It then replaces them with this:

[code_syntax_highlighter type="primary" header="header-text" footer="footer-text"]code-here[/code_syntax_highlighter]

The problem is that the RegEx below currently matches any image inside a <p> tag.

I need to modify it to only match images that have a matching CSS class name = code_syntax_highlighter

So if the image does not have a CSS class of code_syntax_highlighter then it will not be matched and replaced in the JavaScript below.

How can I modify the Regex to require the existence of this CSS class?

function restoreShortcodes2( content ) {
    return content.replace( /(?:<p(?: [^>]+)?>)*(<img [^>]+>)(?:<\/p>)*/g, function( match, image ) {
        var data1 = getAttr( image, 'data-sh-attr' );
        var con = getAttr( image, 'data-sh-code' );

        if ( data1 ) {
            return '<p>[' + short_code_tag + data1 + ']' + con + '[/'+short_code_tag+']</p>';
        }
        return match;
    });
}

1 Answer 1

1

replace your regex with this one

/(<img(\s*(?:\w+=".*")* class=".*code_syntax_highlighter.*" (?:\w+=".*")*)\/*>)/g

which should be

function restoreShortcodes2( content ) {
    return content.replace(/(<img(\s*(?:\w+=".*")* class=".*code_syntax_highlighter.*" (?:\w+=".*")*)\/*>)/g , function( match, image ) {
        var data1 = getAttr( image, 'data-sh-attr' );
        var con = getAttr( image, 'data-sh-code' );

        if ( data1 ) {
            return '<p>[' + short_code_tag + data1 + ']' + con + '[/'+short_code_tag+']</p>';
        }
        return match;
Sign up to request clarification or add additional context in comments.

2 Comments

This works as long as I make sure my image tag has a space at the end before the closing > tag which is fine. The other issue I have is that if my source text has more than 1 image that matches, it replaces all matches with 1 replacement now and before it would replace each match with a replacement. Any ideas why that might not work now? thanks
ok let me try to correct the closing tag to make it robust. about the second issue am taking a deeper look at the code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.