Search code examples
javascripthtmlstringcolorspre

Coloring middle of string in javascript


I have this as a string in a javascript document (taken from a pre tag in my HTML):

sqlString = "UPDATE galleria SET image_description = @image_description WHERE id = " + image.Id + " AND image_id = " + @image_id;

and I wish to color the text that is written within the quotation marks ("). I know I can do this with putting

<span style="color:red;">*text here*</span>

but I'm not sure how to do it. So far I've made an algorithm that gets the positions in the string of the quotation marks (for example in this string, I have 2 variables with the values 12 and 83), but to manipulate the string and post it back so that the above string becomes

sqlString = <span style="color:red;">"UPDATE galleria SET image_description = @image_description WHERE id = "</span> + image.Id + <span style="color:red;">" AND image_id = "</span> + @image_id;

Thanks.


Solution

  • You'd use substring and concatenation. Assuming indexOfStartQuote and indexOfEndingQuote, then:

    sqlString = sqlString.substring(0, indexOfStartQuote) +
                '<span style="color: red">' +
                sqlString.substring(indexOfStartQuote + 1, indexOfEndingQuote + 1) +
                '</span>' +
                sqlString.substring(indexOfEndingQuote + 2);
    

    ...and then use that to set innerHTML on the element.

    You may want to play with the + 1s in there, depending on whether you want the quotes to be in red.


    Side note: I'd advocate using <span class="error"> or some such instead, and doing the styling with a style element or a stylesheet.