Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change style of all occurrences of a string

I want my site title to display in a unique font from the rest of the content every time it appears in a heading, for branding reasons. For simplicity, let's pretend my special font is Courier and my company is called SparklePony. So, a line like,

<h1 class="title">SparklePony Board of Directors</h1>

would show a headline with the word SparklePony in Courier and Board of Directors in my site default font, Arial. (Yes, I know this would be hideous.)

I've tried using a jQuery string replacement, but I don't want to replace the string, I just want to see it in Courier (adding a class to just that word, or something of the like.) Replacing SparklePony with <span class="sparkle-pony">SparklePony</span> caused the whole ugly string with tags and everything to show on my site, rather than adding the class.

Am I doing something wrong with my string replace, or is there a better way to style all occurrences of a string?

like image 741
beth Avatar asked Dec 20 '12 20:12

beth


3 Answers

You can do it like this - specifying the selector you want - #('h1') or by class.

$('.title').html(function(i,v){    
   return v.replace(/SparklePony/g,'<span class="sparkle">SparklePony</span>');
});
​

http://jsfiddle.net/cQjsu/

like image 106
wirey00 Avatar answered Sep 30 '22 05:09

wirey00


Without seeing the code (which would be kinda important in questions like this), best guess is that you're using .text() instead of .html() which would parse the HTML correctly.

like image 29
JJJ Avatar answered Sep 30 '22 05:09

JJJ


It could do with some tidying, but this may be a good starting point: http://jsfiddle.net/c24w/Fznh4/9/.

HTML

<div id="title">Highlight this blah blah HiGhLiGhT THIS blah</div>
<button id="clickme">Click to highlight text</button>

CSS

#title{
  font-family: sans-serif;
  font-size: 20pt;
  margin: 30px 0;
}
span.highlight{
  color: #09f;
  font-weight: bold;
}

JavaScript

function highlightText(element, phrase, allOccurrences, caseSensitive){
  var modifiers = (allOccurrences ? 'g' : '') + (caseSensitive ? '' : 'i');
  var text = element.innerHTML;
  element.innerHTML = text.replace(new RegExp(phrase, modifiers), function(match){
    return '<span class="highlight">' + match + '</span>';
  });
}

var button = document.getElementById('clickme');
var el = document.getElementById('title');

button.onclick = function(){
  highlightText(el, 'highlight this', true, false);
  button.onclick = null;
};
like image 35
c24w Avatar answered Sep 30 '22 05:09

c24w