Change all instances of a word AND update a color with jQuery. Here's what I have at the moment:

70 Views Asked by At

Change all instances of a word AND update the color of ONLY the changed words with jQuery. Here's what I have at the moment:

if($("body").html($("body").html().replace(/Copyright © \d{4}\b/g,"Copyright © 
2018"))){
$(this).css({"color": "red"});
}

I'm sure there's a simple solution and my jquery isn't the best at the moment. I tried adding a class to it and then using the class selector to change it, but I didn't know what to attach the class selector to. So to be clear...

I'm looking for all instances of "Copyright © [1234]" and updating it to the current year and then I want to change the color of those specific instances to red.

Thanks.

2

There are 2 best solutions below

2
The fourth bird On

If the text is inside an element like <p> or <h1> and you can not wrap the match in for example a <span> you could use this example. Note that when Copyright © 2011 is placed directly inside the <body> tag, the <body> tag will get color red.

Using test without anchors will return true if it can find a match in the string. If you want an exact match you could use anchors ^$ to assert the start and the end.

^Copyright © \d{4}$

If there can be whitespace characters at the start or at the end you could \s*:

^\s*Copyright © \d{4}\s*$

let pattern = /Copyright © \d{4}\b/;
let currentYear = (new Date()).getFullYear();
$('body').find("*").filter(function() {
  return pattern.test($(this).text());
}).each(function(i, e) {
  $(e).text($(e).text().replace(pattern, "Copyright © " + currentYear));
  $(e).css({
    "color": "red"
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Copyright © 2011</p>
<div><span>Copyright © 2011A</span></div>
<div>test</div>
<div><span>Copyright © 2011</span></div>

0
Daniel Hayes On

Figured it out. Just one more line of code. Seems obvious now.

https://codepen.io/danielhayespco/pen/qyeagg

$("body").html($("body").html().replace(/Copyright © \d{4}\b/g,"Copyright © 2018"));
$("body").find(":contains('Copyright © 2018')").css("color", "red");