Question

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.

Was it helpful?

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

OTHER TIPS

To replace

var string = '+';
var re = new RegExp(find, 'g');

str = str.replace(re, '');

Title case

function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

Ref : Convert string to title case with JavaScript

You can just use css inside JavaScript. Check this answer.

The full code can be:

function format_str(str) {
    formatted_str = str.replace(/+/g, ' ');
    return '<span style="text-transform: capitalize">'+ formatted_str +'</span>';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top