Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 652
Paladini Avatar asked Jan 16 '26 21:01

Paladini


2 Answers

You can use a simple regex replace

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

Demo: Fiddle

function rtrim(str){
    return str.replace(/\s+$/, '');
}
like image 71
Arun P Johny Avatar answered Jan 19 '26 15:01

Arun P Johny


jQuery doesn't have the methods ltrim or rtrim.

You can do it easily:

function rtrim(str){
    return str.replace(/\s+$/, "");
}
function ltrim(str){
    return str.replace(/^\s+/, "");
}

I don't suggest you add a method on the String prototype.

like image 33
user2194566 Avatar answered Jan 19 '26 16:01

user2194566



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!