admin管理员组文章数量:1319022
The user enters their text in #title
and JQuery converts the string and places it in an input field named #url
. The following code works:
$('#title').on('keyup', function (e) {
e.preventDefault();
var str = $(this).val();
str = str.replace(/\W+/g, '-').toLowerCase();
$('#url').val(str);
});
But here is the issue, If i enter Big "Fish" Little "Fish"
JQuery will convert this to: big-fish-little-fish-
. So the question is how do i remove the last - at the end. Could i use something like before()
and then it will do the replacement?
The user enters their text in #title
and JQuery converts the string and places it in an input field named #url
. The following code works:
$('#title').on('keyup', function (e) {
e.preventDefault();
var str = $(this).val();
str = str.replace(/\W+/g, '-').toLowerCase();
$('#url').val(str);
});
But here is the issue, If i enter Big "Fish" Little "Fish"
JQuery will convert this to: big-fish-little-fish-
. So the question is how do i remove the last - at the end. Could i use something like before()
and then it will do the replacement?
3 Answers
Reset to default 7Instead of doing something to replace the final -
you could also use a negative lookahead to avoid replacing anything that occurs at the end of the string and then use a subsequent statement to replace any non word char that occurs at the end with an empty space.
$('#title').on('keyup', function (e) {
//alert("key up");
e.preventDefault();
var str = $(this).val();
str = str.replace(/\W+(?!$)/g, '-').toLowerCase();
str = str.replace(/\W$/, '').toLowerCase();
$('#url').val(str);
});
Example Fiddle: https://jsfiddle/ue1vedez/
How about to add another replace()
which would remove the ending dash
str = str.replace(/\W+/g, '-').replace(/\-$/, '').toLowerCase();
$('#title').on('keyup', function (e) {
//alert("key up");
e.preventDefault();
var str = $(this).val();
str = str.replace(/\W+(?!$)/g, '-').toLowerCase();
str = str.replace(/\W+$/, '').toLowerCase();
$('#url').val(str);
});
Use W+ instead just W, because it so not allow put '-' in last when type various characters into last
本文标签: javascriptReplacing special characters with dashesStack Overflow
版权声明:本文标题:javascript - Replacing special characters with dashes - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742050807a2418053.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论