最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replacing special characters with dashes - Stack Overflow

programmeradmin1浏览0评论

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?

Share Improve this question asked Apr 11, 2016 at 19:07 SickaaronSickaaron 4481 gold badge12 silver badges21 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

Instead 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

发布评论

评论列表(0)

  1. 暂无评论