最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change the color of strings affected by regex on (document).ready - Stack Overflow

programmeradmin4浏览0评论

So I what I'm trying to acplish here, is to change the color of words affected by some regex.

$(document).ready(function(){

  container = $("#modal_container section").text();
  hashtags = /\#\w+/g;
  var container_hash = container.match(hashtags);
  $(container_hash).css({'color':'red'}); 
  //We're grabbing the words, but how can I change the color?
  alert(container_hash);

 });

Here's a fiddle / to make it more clear.

Thanks

So I what I'm trying to acplish here, is to change the color of words affected by some regex.

$(document).ready(function(){

  container = $("#modal_container section").text();
  hashtags = /\#\w+/g;
  var container_hash = container.match(hashtags);
  $(container_hash).css({'color':'red'}); 
  //We're grabbing the words, but how can I change the color?
  alert(container_hash);

 });

Here's a fiddle http://jsfiddle/vuDzC/2/ to make it more clear.

Thanks

Share asked Apr 20, 2013 at 23:04 AaronAaron 1811 gold badge4 silver badges12 bronze badges 1
  • You can't change the colour of individual words in the sense of arbitrarily selecting some of an element's text. You'd need to wrap each word in, say, span elements, and then change the colour of each span. – nnnnnn Commented Apr 20, 2013 at 23:06
Add a ment  | 

3 Answers 3

Reset to default 5

You can't change color of textNodes/texts, you should wrap the matching text with an element and then style that element.

$("#modal_container section p").html(function(_, html) {
   return html.replace(/(\#\w+)/g, '<span class="red">$1</span>');   
});

http://jsfiddle/vuDzC/4/

This sort of does that you're looking for (or should be a good enough example):

<script type="text/javascript">
    $(document).ready(function(){
        var text = $("#modal_container").html();
        var myRegExp = new RegExp('\\#\\w+','gi');
        var newtext = text.replace(myRegExp,'<span style="color:red;">$&</span>');
        $("#empty").html(newtext);
    });
</script>
<div id="modal_container">
    #works<br />
    # Desnt Work<br />
    Not Even Close<br />
</div>
<div id="empty" style="margin-top:30px;">
</div>
 $(function(){

  var container = $("#modal_container section");
  var htmlWrappedHashtags = container.html().replace(/\(#\w+)/g, '<span class="red">$1</span>');
  container.html(htmlWrappedHashtags);

  $(".red").css({'color':'red'}); // or better: include ".red {color: red;}" into your CSS

 });
发布评论

评论列表(0)

  1. 暂无评论