Javascript Clean URL Regex

I am creating CMS news sections with several fields, but the Title and Link URL fields are especially important for this issue. When the user enters the title of the article, I want Javascript / jQuery to replace the text from the Title field and create a “clean” URL fragment, removing any spaces and strange characters with dashes (-).

eg.

Chris FUN new article (title)

kris-fun-new-article (URL Link)

Here is the code, but I can't figure out how to replace a few spaces and special characters

$ ('# title'). keyup (function () {
    var ref = $ (this) .val (). toLowerCase (). replace ('\', '-');
    $ ('# reference'). val (ref);
});

In addition, as in the title “Chris' New Article,” the regular expression should replace “Chris” (quote and space) with “chris” (one stroke). Essentially, find out if there are two special characters next to each other, and replace them with one dash. DO NOT like this "kris - fun-new-article".

Thank you in advance

+5
source share
5 answers

Samir Talwar's answer is correct, except that at the end of the regular expression there must be a /.../g flag to indicate global correspondence. Without /.../g, only the first match is replaced.

Torez, here is the updated version of your function:

$('#title').keyup(function(){
    var ref = $(this).val().toLowerCase().replace(/[^a-z0-9]+/g,'-');
    $('#reference').val(ref);
});

(, , , , .)

+10

Try:

function slug(str) {
  if (!arguments.callee.re) {
    // store these around so we can reuse em.
    arguments.callee.re = [/[^a-z0-9]+/ig, /^-+|-+$/g];
    // the first RE matches any sequence of characters not a-z or 0-9, 1 or more 
    // characters, and gets replaced with a '-'  the other pattern matches '-'
    // at the beginning or end of a string and gets replaced with ''
  }
  return str.toLowerCase()
   // replace all non alphanum (1 or more at a time) with '-' 
   .replace(arguments.callee.re[0], '-')
   // replace any starting or trailing dashes with ''
   .replace(arguments.callee.re[1],'');
}

slug("Kris' FUN new Article ");
// "kris-fun-new-article"
+4

- g - , - (+ = , ).

, - replace(/[' {insert further chars you care about here}]+/g,'-')

+1

, , , , :

[specials charaters " "]+

0

?

str = str.toLowerCase().replace(/[^a-z0-9]+/, '-');

, , + , .

0

All Articles