RGBK
RGBK

Reputation: 2048

Jquery — Regex a URL slug into a capitalized sentence?

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

Answers (3)

Rion Williams
Rion Williams

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; 
   }

Working Example - Updated

Upvotes: 2

RGBK
RGBK

Reputation: 2048

OK, this works 100%:

http://jsfiddle.net/Y9WQC/1/

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

Malice
Malice

Reputation: 3977

Comparing jQuery with PHP isn't a particularly fair comparison but rather than get into that I'll just direct you towards this question. It's doing the opposite operation but you might get some help with your issue from it.

Upvotes: 0

Related Questions