Fernando Paladini Fernando Paladini - 1 month ago 13
Javascript Question

Trim blank spaces from the right in jQuery

I see the

trim
method in jQuery, but I can't find, in its documentation, how to trim blank spaces from only the right of the string.

As an example, if I have:

"foobar " "foo " " foo bar "


Trimming the spaces from the right of the string results in:

"foobar" "foo" " foo bar"


Is there any method in jQuery to trim the spaces from the right? I mean, something like
ltrim
and
rtrim
?

Answer

You can use a simple regex replace

string.replace(/\s+$/, '')

Demo: Fiddle

function rtrim(str){
    return str.replace(/\s+$/, '');
}
Comments