简体   繁体   English

javascript-设置字符颜色从一个到另一个

[英]javascript - Set color of characters from one to another

Using Javascript, I want to construct myFunction() such that this HTML code: 我想使用Javascript构造myFunction() ,以便此HTML代码:

<body onload="myFunction();">
    Hello world! This is "'my' webpage"!<br>
    Do you know what "Javascript" is?
</body>

will be converted to this HTML code: 将被转换为以下HTML代码:

<body onload="myFunction();">
    Hello world! This is <a style="color: blue;">"'my' webpage"</a>!<br>
    Do you know what <a style="color: blue;">"Javascript"</a> is?
</body>

So in other words, I want all characters between (double) inverted commas "" to be blue. 因此,换句话说,我希望(双)反逗号""之间的所有字符都是蓝色。

I tried this: 我尝试了这个:

function myFunction() {
    var body_content = document.getElementsByTagName("body")[0].innerHTML;
    document.getElementsByTagName("body")[0].innerHTML = 
        body_content.replace(/\"/g, '<a style="color: Blue;">"');
}

But it made everything blue after the first double inverted comma in the body. 但是,在体内第一个双反逗号后,一切都变成了蓝色。

How do I construct myFunction() ? 如何构造myFunction()

change Your regular expression, 更改您的正则表达式

  var body_content = document.getElementsByTagName("body")[0].innerHTML;
  document.getElementsByTagName("body")[0].innerHTML = 
  body_content.replace(/"([^\"]*)"/g,"<a style='color: Blue;'>\"$1\"</a>");

jsFiddle for this example 此示例的jsFiddle

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

相关问题 JavaScript:用另一个字符替换一组字符 - JavaScript: replace a set of characters with another one 将javascript变量从一个iframe设置为另一个 - Set javascript variable from one iframe to another Javascript,将div颜色设置为另一种divs颜色 - Javascript, set div color to another divs color JavaScript过程来查找一个字符串中的字符,而不是另一字符串中的字符 - JavaScript procedure to find the characters that are in one string but not in another 将 javascript 计算样式从一个元素设置/复制到另一个元素 - Set / Copy javascript computed style from one element to another 如何设置JavaScript变量或从其他函数重用一个 - How to set a javascript variable or reuse one from another function CRM 2011 JavaScript-从一个字段修改日期并设置为另一个 - CRM 2011 JavaScript - Modify Date From One Field And Set To Another 将在javascript中设置的参数从一个jsp发送到另一个jsp - Send parameters that are being set in a javascript from one jsp to another jsp 一个div的边框是使用javascript的另一个的颜色 - border of one div to be the color of another with javascript 如何使用 JavaScript 将一个字符串中找到的任何字符替换为另一个字符串 - How to use JavaScript to replace any characters found within one string from another string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM