Search code examples
javascriptstringreplacerhino

Rhino JavaScript Method of Replacing Character & TitleCase


I need to convert Paid Search terms into a normal sentence case string. For example, the Google referring URL would contain the following:

q=javascript+stackoverlow+HELP

My current code escapes the value, but I'm thinking I need a simple function to remove the plus signs and set the case properly so that it looks like this:

Javascript Stackoverflow Help

Here is my current setup.

if (landing.referrer.domain.match(/google\.com/)) {
  return unescape(landing.referrer.param('q'));
} else if (landing.referrer.domain.match(/yahoo\.com/)) {
  return unescape(landing.referrer.param('p')); 
} else if (landing.referrer.domain.match(/bing\.com/)) {
  return unescape(landing.referrer.param('q'));  
}

I only need to worry about English (Latin) character set.


Solution

  • I would use:

    if (!String.prototype.toTitleCase) {
        String.prototype.toTitleCase = function() {
            return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
        }
    }
    

    And:

    function getSearchTerms(link) {
        link = link.substring(link.indexOf("=") + 1);
    
        var arr = link.split("+");
        for (var i = 0; i < arr.length; i++) {
            arr[i] = arr[i].toTitleCase();
        }
    
        return arr.join(" ");
    }
    

    JSFiddle DEMO