Chapsterj
Chapsterj

Reputation: 6625

replace empty space with dash only if trailing string

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

Upvotes: 0

Views: 3786

Answers (3)

dtanders
dtanders

Reputation: 1845

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

Upvotes: 0

Andrea Scarcella
Andrea Scarcella

Reputation: 3323

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

DEMO

Upvotes: 1

qwertymk
qwertymk

Reputation: 35274

DEMO

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

\b (word boundaries) info

jQuery.trim() api

Upvotes: 1

Related Questions