Max Max - 1 year ago 63
jQuery Question

change color of matches that start with # in string Js or Jquery

I am working in a string in php

$string="Hello #today is #Sunday #everywhere";

where with ths function (PHP) I replace the colors of the hashtahgs matches in the string.

function hashtag_color($string) {
return preg_replace('/#(\w+)/', "<span class=OrangeColor>#$1</span>", $string);

What I want is to do the same but in
. Because I am editing the output string with
and the
succcess: function(data){}
returns plain text which need to be coloured again.

Answer Source

Use /#\w*/g regex to found all the words starting with # from a string.

Please check working snippet

var mainString = "Hello #today is #Sunday #everywhere";
r = /#\w*/g; // big letter with word symbols, global search
function f(x){
  return '<span class="OrangeColor">'+x+'</span>' // rewrited
h = mainString.replace(r,f); //replace
$("#mainString").html(h); //set
.OrangeColor {
  background-color: orange;
<script src=""></script>
<p id="mainString"></p>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download