Reputation: 1912
I am building a CMS news sections with a few fields but the ones notably needed for this question are the "Title" and "URL Reference" fields. When a user enters in an article title I want Javascript/jQuery to replace the text from the Title field and create a "clean" URL fragment by removing any spaces and weird characters with a dash(-).
e.g.
Kris' FUN new Article (Title)
kris-fun-new-article (URL Reference)
Here is the code, but I can't seem to figure out how to replace multiple spaces and special characters
$('#title').keyup(function(){ var ref = $(this).val().toLowerCase().replace('\ ','-'); $('#reference').val(ref); });
Also, like in the title "Kris' FUN new Article" the regex should replace "Kris' "(quote and space) with "kris-"(one dash). Essentially recognize if there are two special characters beside one another and replace is with one dash. NOT like this "kris--fun-new-article".
Thanks in advance
Upvotes: 7
Views: 16447
Reputation: 981
Samir Talwar's answer is correct, except that there needs to be a flag /.../g on the end of the regular expression to indicate a global match. Without the /.../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);
});
(Sorry, Samir, I would have just commented on your response, except I do not have enough reputation points yet.)
Upvotes: 13
Reputation: 14330
How's this?
str = str.toLowerCase().replace(/[^a-z0-9]+/, '-');
Should replace everything that's not a letter or a number with a dash, and the +
means it'll take more than one of them at a time.
Upvotes: 0
Reputation: 75872
You need the global flag - g - on the regex, and some kind of quantifier for multiples (+ = one or more matches, seems right here).
So something like replace(/[' {insert further chars you care about here}]+/g,'-')
Upvotes: 1
Reputation: 106402
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"
Upvotes: 5
Reputation: 46985
I think you want a character class that contains the special characters and the space then you can specify one or more instances of the character class like so:
[specials charaters " "]+
and replace that match with a dash
Upvotes: 0