开发者

Jquery — Regex a URL slug into a capitalized sentence?

开发者 https://www.devze.com 2023-02-19 01:38 出处:网络
Hi there I\'m trying t开发者_StackOverflowo figure out how to convert this-is-my-slug to: This Is My Slug

Hi there I'm trying t开发者_StackOverflowo 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?


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


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.


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消