1

I have the following RegEx:

$('.my-selector').each(function(){
  var t = $(this).text(),
      id = t.toLowerCase().replace(/\s+/g, '-');
  id  = id.replace(/[^a-zA-Z0-9-]/g, "");
});

This repalces all spaces with a - and then removes any character that isn't a-z, 0-9 or -. This works but I noticed one thing, if I have a trailing space it becomes a -. For examples. My (test) string becomes my-test-string-

How to I remove the last - (or ) from the very end of the string?

L84
  • 45,514
  • 58
  • 177
  • 257
  • possible duplicate of http://stackoverflow.com/questions/10032024/how-to-remove-leading-and-trailing-white-spaces-from-a-given-html-string – Edi Feb 24 '16 at 05:40

2 Answers2

1

The simplest option would be to chain the .trim() method before replacing the whitespace. In doing so, the trailing whitespace is removed.

string.toLowerCase().trim().replace(/\s+/g, '-')

It would output my-test-string:

var text = 'My (test) string ';
var id = text.toLowerCase().trim().replace(/\s+/g, '-')
             .replace(/[^a-zA-Z0-9-]/g, '');

console.log(id); // my-test-string

Of course, you could alternatively just use a negative lookahead in order to prevent the whitespace at the end from being replaced:

string.toLowerCase().replace(/\s+(?!\s*$)/g, '-')
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
1

Try

$('.my-selector').each(function(){
  var t = $(this).text(),
      id = t.toLowerCase().replace(/\s+/g, '-');
  id  = id.replace(/[^a-zA-Z0-9-]/g, "").replace(/-$/, '');
});