Tor*_*rez 5 javascript regex jquery
我正在构建一个包含几个字段的CMS新闻部分,但这个问题特别需要的是"标题"和"URL参考"字段.当用户输入文章标题时,我希望Javascript/jQuery替换Title字段中的文本,并通过删除任何空格和带有短划线( - )的奇怪字符来创建"干净"的URL片段.
例如
Kris'FUN新文章(标题)
kris-fun-new-article(URL参考)
这是代码,但我似乎无法弄清楚如何替换多个空格和特殊字符
$('#title').keyup(function(){
var ref = $(this).val().toLowerCase().replace('\ ','-');
$('#reference').val(ref);
});
此外,就像标题"Kris'FUN新文章"一样,正则表达式应该用"kris - "(一个破折号)代替"Kris"(引用和空格).基本上可以识别彼此之间是否有两个特殊字符,并且替换为一个破折号.不喜欢这个"kris - fun-new-article".
提前致谢
Pau*_*ury 10
Samir Talwar的回答是正确的,除了在正则表达式的末尾需要一个标志/.../g来表示全局匹配.没有/.../g只会替换第一个匹配.
Torez,这是您的功能的更新版本:
$('#title').keyup(function(){
var ref = $(this).val().toLowerCase().replace(/[^a-z0-9]+/g,'-');
$('#reference').val(ref);
});
Run Code Online (Sandbox Code Playgroud)
(对不起,Samir,我刚刚评论过你的回复,但我还没有足够的声望点.)
尝试:
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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10354 次 |
| 最近记录: |