Search code examples
jqueryhtmlcoldfusioncoldfusion-11

How to insert photo after second paragraph using coldfusion


I have a variable that has a blog post with html characters in it. The content would look something like this.

I output content from a query to the page.

<cfoutput>#queryvar.myvar#</cfoutput>

I would like to know how to insert a photo after the second paragraph.

<img src="someimage.jpg">

I am not against using jquery. Any help would be greatly appreciated.


Solution

  • A simple solution to your problem is to find the position of the second paragraph end tag /p> then insert your image at that position with string concatenation.

    <cfset myimg = "<div><img src='someimage.jpg'></div>" />
    <cfset mycontent = '#queryvar.myvar#' />
    
    <cfset firstMatch = find("/p>", mycontent, 0) />
    
    <cfif firstMatch gt 0 >
      <cfset secondMatch = find("/p>", mycontent, firstMatch + 1) />
    <cfelse>
      <cfset secondMatch = 0 />
    </cfif>
    
    <cfif secondMatch gt 0 >
      <cfset mycontent = left(mycontent, secondMatch + 3) 
                            & myimg 
                            & right(mycontent, (len(mycontent) - (secondMatch + 3))) />
    </cfif>  
    
    <cfoutput>#mycontent#</cfoutput>