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
?
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
?
- There is no rtrim or ltrim in jQuery core. There are plugins or you can just use a basic reg exp to do it. – epascarello Commented Oct 16, 2013 at 3:37
- Thanks @epascarello . I think that's a little thing that can be improved in the newest versions of jQuery - will be very useful. – Paladini Commented Oct 16, 2013 at 3:41
- 1 They are not going to add that to jQuery core. Proof: bugs.jquery./ticket/9542 – epascarello Commented Oct 16, 2013 at 5:12
4 Answers
Reset to default 10You can use a simple regex replace
string.replace(/\s+$/, '')
Demo: Fiddle
function rtrim(str){
return str.replace(/\s+$/, '');
}
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.
you could do:
String.prototype.rtrim = function() {
return this.replace(/\s+$/,"");
}
var str = "test ";
console.log(str.rtrim());
You can do something like this too:
"foobar ".substring(0,"foobar ".length-1)
I'm not really into jQuery so you may need to use
var yourstring ="something ";