Take the 2-minute tour ×

I'm using regEx and replace method to replace an empty space with a dash but I only want this to happen if there is a following character. For example if the input field looked like this then replace empty space between temp and string with dash

input = "temp string";

if it looked like this then it would just remove the empty space

input = "temp  ";

here is my regEx replace right now. But not sure how to check if there are trailing characters.

input.value.replace(/\s+/g, '-');
share|improve this question
String.trim. –  Rob W Apr 2 '12 at 22:03
@RobW: jQuery.trim –  qwertymk Apr 2 '12 at 22:09
add comment

3 Answers

up vote 0 down vote accepted


input = $.trim(input.replace(/\b \b/g, '-'));

\b (word boundaries) info

jQuery.trim() api

share|improve this answer
@Starx ... really? –  qwertymk Apr 2 '12 at 22:07
Nice worked, thanks –  Chapsterj Apr 2 '12 at 22:12
Your answer looks a lot better without the loudness. –  Starx Apr 2 '12 at 22:13
What does the b \b do –  Chapsterj Apr 2 '12 at 22:13
-1, no need for jQuery trim there –  Starx Apr 2 '12 at 22:19
add comment

This should do the trick: the first replace takes care of the trailing spaces (if there's at least one) the second one performs your original replacement

str.replace(/\s+$/g,'').replace(/\s+/g, '-');


share|improve this answer
add comment

/\s+$/ only finds trailing spaces, so add .replace(/\s+$/, '') after .value

share|improve this answer
I added this to the end of my above code and it still just adds the dash –  Chapsterj Apr 2 '12 at 22:10
Fixed. Sorry about that. –  dtanders Apr 3 '12 at 15:50
add comment

Your Answer


