我正在构建一个包含几个字段的CMS新闻栏目,但这个问题特别需要的是“标题”和“URL参考”字段。当用户输入文章标题时,我希望Javascript / jQuery替换Title字段中的文本,并通过删除任何空格和带有短划线( - )的奇怪字符来创建“干净”的URL片段。
e.g。
Kris'FUN新文章(标题)
kris-fun-new-article(网址参考)
这是代码,但我似乎无法弄清楚如何替换多个空格和特殊字符
$('#title').keyup(function(){ var ref = $(this).val().toLowerCase().replace('\ ','-'); $('#reference').val(ref); });
此外,就像标题“Kris'FUN新文章”一样,正则表达式应该用“kris - ”(一个短划线)代替“Kris”(引用和空格)。基本上可以识别彼此之间是否有两个特殊字符,并且替换为一个破折号。不喜欢这个“kris - fun-new-article”。
提前致谢
答案 0 :(得分:10)
Samir Talwar的回答是正确的,除了在正则表达式的末尾需要一个标志/.../g来表示全局匹配。没有/.../g只会替换第一个匹配。
Torez,这是您的功能的更新版本:
$('#title').keyup(function(){
var ref = $(this).val().toLowerCase().replace(/[^a-z0-9]+/g,'-');
$('#reference').val(ref);
});
(对不起,Samir,我刚刚评论过你的回复,但我还没有足够的声望点。)
答案 1 :(得分:4)
尝试:
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"
答案 2 :(得分:1)
你需要正则表达式的全局标志 - g - 以及倍数的某种量词(+ =一个或多个匹配,似乎就在这里)。
类似于replace(/[' {insert further chars you care about here}]+/g,'-')
答案 3 :(得分:0)
我认为您需要一个包含特殊字符和空格的字符类,然后您可以指定一个或多个字符类实例,如下所示:
[specials charaters " "]+
并用破折号替换该匹配
答案 4 :(得分:0)
这是怎么回事?
str = str.toLowerCase().replace(/[^a-z0-9]+/, '-');
应该用破折号替换不是字母或数字的所有内容,而+
表示一次只能使用多个字母。