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?

1

2 Answers 2

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, '-')
Sign up to request clarification or add additional context in comments.

Comments

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(/-$/, '');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.