Reputation: 2048
Hi there I'm trying to figure out how to convert
this-is-my-slug
to:
This Is My Slug
in Jquery?!
I know PHP is awesome with this, but jQuery maybe not?
Upvotes: 2
Views: 552
Reputation: 76597
This should do it for you: (This was a simple previous example)
var str = "this-is-my-slug";
str = str.toLowerCase().replace(/-/,' ').replace(/\b[a-z]/g, convert);
function convert() {
return arguments[0].toUpperCase();
}
Here it is in function form - the entire word and single word conversions:
//Converts and Formats entire string
function Convert(test)
{
var formatted = test.toLowerCase().replace(/-/g,' ');
var array = test.split(" ");
var output = "";
for (i=0;i<array.length;i++)
{
output += ConvertString(array[i]);
}
return output;
}
//Formats individual words
function ConvertString(string)
{
var str = string;
str = str.toLowerCase().replace(/-/g,' ').replace(/\b[a-z]/g, convert);
function convert() {
return arguments[0].toUpperCase();
}
return str;
}
Upvotes: 2
Reputation: 2048
OK, this works 100%:
var string = "this-is-a-slug";
convert = string.replace(/-/g," ");
function ucwords (str) {
// http://kevin.vanzonneveld.net
// + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// + improved by: Waldo Malqui Silva
// + bugfixed by: Onno Marsman
// + improved by: Robin
// + input by: James (http://www.james-bell.co.uk/)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: ucwords('kevin van zonneveld');
// * returns 1: 'Kevin Van Zonneveld'
// * example 2: ucwords('HELLO WORLD');
// * returns 2: 'HELLO WORLD'
return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
var result = ucwords(convert)
$("div").text(result);
<div>my new string will output here</div>
Upvotes: 0