简体   繁体   English

在JavaScript中为字符串上色

[英]Coloring middle of string in javascript

I have this as a string in a javascript document (taken from a pre tag in my HTML): 我在javascript文档中将其作为字符串(取自HTML中的pre标签):

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 到目前为止,我已经制定了一种算法来获取引号字符串中的位置(例如,在该字符串中,我有2个变量,其值分别为12和83),但是要对字符串进行处理并将其发布回去,以便上面的字符串变成

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. 谢谢。

You'd use substring and concatenation. 您将使用substring和串联。 Assuming indexOfStartQuote and indexOfEndingQuote , then: 假设indexOfStartQuoteindexOfEndingQuote ,则:

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. ...然后使用它在元素上设置innerHTML

You may want to play with the + 1 s in there, depending on whether you want the quotes to be in red. 您可能需要在其中加上+ 1 ,这取决于您是否希望引号用红色表示。


Side note: I'd advocate using <span class="error"> or some such instead, and doing the styling with a style element or a stylesheet. 旁注:我主张使用<span class="error">或类似的替代方法,并使用style元素或样式表进行样式设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM