L84
L84

Reputation: 46308

RegEx to Remove Trailing Space

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?

Upvotes: 1

Views: 676

Answers (2)

Josh Crozier
Josh Crozier

Reputation: 240878

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, '-')

Upvotes: 1

CzarJohn Demafeliz
CzarJohn Demafeliz

Reputation: 328

Try

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

Upvotes: 1

Related Questions