Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Wednesday, January 20, 2016

How to convert a Title to a URL slug in jQuery?

How to convert a Title to a URL slug in jQuery?


I'm working on an app in CodeIgniter, and I am trying to make a field on a form dynamically generate the URL slug. What I'd like to do is remove the punctuation, convert it to lowercase, and replace the spaces with hyphens. So for example, Shane's Rib Shack would become shanes-rib-shack.

Here's what I have so far. The lowercase part was easy, but the replace doesn't seem to be working at all, and I have no idea to remove the punctuation:

$("#Restaurant_Name").keyup(function(){      var Text = $(this).val();      Text = Text.toLowerCase();      Text = Text.replace('/\s/g','-');      $("#Restaurant_Slug").val(Text);      });  

Answer by karim79 for How to convert a Title to a URL slug in jQuery?


All you needed was a plus :)

$("#Restaurant_Name").keyup(function(){          var Text = $(this).val();          Text = Text.toLowerCase();          var regExp = /\s+/g;          Text = Text.replace(regExp,'-');          $("#Restaurant_Slug").val(Text);          });  

Answer by Philippe Leybaert for How to convert a Title to a URL slug in jQuery?


First of all, regular expressions should not have surrounding quotes, so '/\s/g' should be /\s/g

In order to replace all non-alphanumerical characters with dashes, this should work (using your example code):

$("#Restaurant_Name").keyup(function(){          var Text = $(this).val();          Text = Text.toLowerCase();          Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');          $("#Restaurant_Slug").val(Text);          });  

That should do the trick...

Answer by Peter Boughton for How to convert a Title to a URL slug in jQuery?


I have no idea where the 'slug' term came from, but here we go:

function convertToSlug(Text)  {      return Text          .toLowerCase()          .replace(/ /g,'-')          .replace(/[^\w-]+/g,'')          ;  }  

First replace will change spaces to hyphens, second replace removes anything not alphanumeric, underscore, or hyphen.

If you don't want things "like - this" turning into "like---this" then you can instead use this one:

function convertToSlug(Text)  {      return Text          .toLowerCase()          .replace(/[^\w ]+/g,'')          .replace(/ +/g,'-')          ;  }  

That will remove hyphens (but not spaces) on the first replace, and in the second replace it will condense consecutive spaces into a single hyphen.

So "like - this" comes out as "like-this".

Answer by Junaid Ali Qureshi for How to convert a Title to a URL slug in jQuery?


private string ToSeoFriendly(string title, int maxLength) {      var match = Regex.Match(title.ToLower(), "[\\w]+");      StringBuilder result = new StringBuilder("");      bool maxLengthHit = false;      while (match.Success && !maxLengthHit) {          if (result.Length + match.Value.Length <= maxLength) {              result.Append(match.Value + "-");          } else {              maxLengthHit = true;              // Handle a situation where there is only one word and it is greater than the max length.              if (result.Length == 0) result.Append(match.Value.Substring(0, maxLength));          }          match = match.NextMatch();      }      // Remove trailing '-'      if (result[result.Length - 1] == '-') result.Remove(result.Length - 1, 1);      return result.ToString();  }  

Answer by user175569 for How to convert a Title to a URL slug in jQuery?


I create a plugin to implement in most of languages: http://leocaseiro.com.br/jquery-plugin-string-to-slug/

Default Usage:

$(document).ready( function() {      $("#string").stringToSlug();  });  

Is very easy has stringToSlug jQuery Plugin

Answer by Taranttini for How to convert a Title to a URL slug in jQuery?


var slug = function(str) {    str = str.replace(/^\s+|\s+$/g, ''); // trim    str = str.toLowerCase();      // remove accents, swap ? for n, etc    var from = "??áäâ??éë??í?î??óöô?úü??ç?/_,:;";    var to   = "aaaaaeeeeeiiiiooooouuuunc------";    for (var i=0, l=from.length ; i

and try

slug($('#field').val())  

original by: http://dense13.com/blog/2009/05/03/converting-string-to-slug-javascript/

Answer by Marko Ranković for How to convert a Title to a URL slug in jQuery?


//  //  jQuery Slug Plugin by Perry Trinier (perrytrinier@gmail.com)  //  MIT License: http://www.opensource.org/licenses/mit-license.php    jQuery.fn.slug = function(options) {  var settings = {      slug: 'slug', // Class used for slug destination input and span. The span is created on $(document).ready()       hide: true   // Boolean - By default the slug input field is hidden, set to false to show the input field and hide the span.   };    if(options) {      jQuery.extend(settings, options);  }    $this = $(this);    $(document).ready( function() {      if (settings.hide) {          $('input.' + settings.slug).after("");          $('input.' + settings.slug).hide();      }  });    makeSlug = function() {          var slug = jQuery.trim($this.val()) // Trimming recommended by Brooke Dukes - http://www.thewebsitetailor.com/2008/04/jquery-slug-plugin/comment-page-1/#comment-23                      .replace(/\s+/g,'-').replace(/[^a-zA-Z0-9\-]/g,'').toLowerCase() // See http://www.djangosnippets.org/snippets/1488/                       .replace(/\-{2,}/g,'-'); // If we end up with any 'multiple hyphens', replace with just one. Temporary bugfix for input 'this & that'=>'this--that'          $('input.' + settings.slug).val(slug);          $('span.' + settings.slug).text(slug);        }    $(this).keyup(makeSlug);    return $this;      };  

This helped me with the same problem !

Answer by MGE for How to convert a Title to a URL slug in jQuery?


You can use your own function for this.

try it: http://jsfiddle.net/xstLr7aj/

function string_to_slug(str) {    str = str.replace(/^\s+|\s+$/g, ''); // trim    str = str.toLowerCase();      // remove accents, swap ? for n, etc    var from = "?áäâ?éë??í?î?óöô?úü??ç?/_,:;";    var to   = "aaaaeeeeiiiioooouuuunc------";    for (var i=0, l=from.length ; i

Answer by Alexander Ivashchenko for How to convert a Title to a URL slug in jQuery?


function slugify(text){    return text.toString().toLowerCase()      .replace(/\s+/g, '-')           // Replace spaces with -      .replace(/[^\u0100-\uFFFF\w\-]/g,'-') // Remove all non-word chars ( fix for UTF-8 chars )      .replace(/\-\-+/g, '-')         // Replace multiple - with single -      .replace(/^-+/, '')             // Trim - from start of text      .replace(/-+$/, '');            // Trim - from end of text  }  

*based on https://gist.github.com/mathewbyrne/1280286

now you can transform this string:

Barack_Obama       ?????_????? ~!@#$%^&*()+/-+?><:";'{}[]\|`  

into:

barack_obama-?????_?????  

applying to your code:

$("#Restaurant_Name").keyup(function(){      var Text = $(this).val();      Text = slugify(Text);      $("#Restaurant_Slug").val(Text);  });  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.