Max Max - 1 month ago 5
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
JQuery
or
JS
. Because I am editing the output string with
àjax
and the
succcess: function(data){}
returns plain text which need to be coloured again.

Answer

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="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="mainString"></p>