我将其作为 javascript 文档中的字符串(取 self 的 HTML 中的 pre 标记):
sqlString = "UPDATE galleria SET image_description = @image_description WHERE id = " + image.Id + " AND image_id = " + @image_id;
并且我希望为引号 (") 内的文本着色。我知道我可以通过放置
来做到这一点<span style="color:red;">*text here*</span>
但我不知道该怎么做。到目前为止,我已经制作了一个算法来获取引号字符串中的位置(例如,在这个字符串中,我有 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;
谢谢。
最佳答案
你会使用 substring
和串联。假设 indexOfStartQuote
和 indexOfEndingQuote
,然后:
sqlString = sqlString.substring(0, indexOfStartQuote) +
'<span style="color: red">' +
sqlString.substring(indexOfStartQuote + 1, indexOfEndingQuote + 1) +
'</span>' +
sqlString.substring(indexOfEndingQuote + 2);
...然后用它来设置 innerHTML
在元素上。
你可能想玩一下 + 1
就在那儿,这取决于您是否希望引号为红色。
旁注:我提倡使用 <span class="error">
或类似的东西,并使用 style
进行样式设置元素或样式表。
关于javascript - 在javascript中着色字符串的中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15427902/