Question

Let's say you are Apple... and sitewide you want every instance of iPod to always be proper case and structured to preserve the branding. I have a similar issue with a company that is not apple at all but has the same branding challenge.

So even if someone types IPOD or ipod or iPoD in the CMS running the site, it will appear correctly always as iPod

Even if there is a text-transform CSS on a headline making everything uppercase like IPOD ETC ETC, it will force the i lower case to be iPOD ETC ETC.

Even if there are plurals or variants like ipods, IPODAGE, iPoDdInG... and any bastardization of it will convert to the proper case - iPods, iPodage, iPodding

I've done some experimenting with the following script I found on jsfiddle and I'm not having much luck although I'm fairly unschooled with js in general.

http://jsfiddle.net/x9BSn/2/

I'm already pulling in jquery for a number of other things in the site so I am fine with utilizing it.

Was it helpful?

Solution

Just modified Shmiddty's solution a bit

$.fn.changeWord = function (str, className) {
    var regex = new RegExp(str, "gi");
    return this.each(function () {
        this.innerHTML = this.innerHTML.replace(new RegExp('(' + str+ '(?=(?:[^\>]|\<[^\<]*\>)*$))', 'gi'), "<span class='"+className+"'>$1</span>");
    });
};

$('#myDiv').changeWord('specialWord', 'sw');

DEMO

OTHER TIPS

Here is (I believe) a working version: http://jsfiddle.net/x9BSn/11/

$.fn.changeWord = function (str, className) {
    var regStr = str + "(?=(?:[^\>]|\<[^\<]*\>)*$)";
    var regex = new RegExp(regStr, "gi");
    var txt = this.html();
    txt = txt.replace(regex, function(matched) {
            return "<span class='" + className + "'>" + str+ "</span>";
    });
    this.html(txt);
};

$('#myDiv').changeWord('specialWord', 'sw');

It will replace all instances of str (case invariant) that aren't enclosed in a tag (< ... >) with str (with the desired case).

So, if you wanted it to be "SpEcialWorD", you would accomplish that with:

$('#myDiv').changeWord('SpEcialWorD', 'sw');

as demonstrated here: http://jsfiddle.net/x9BSn/13/

You can then use some css like this to add to that content:

.sw:after{
    content: "TM";
    vertical-align:super;
    font-size:.5em;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top