views:

69

answers:

3

I have a string of varying length and is usually followed by white spaces (of varying length based on he string).

i.e. - the string is always 20 characters long

var data = "DUR IT R4356        " //with 8 trailing

or the string could be

var data = "11& 444 DTF# 5676   " //with 3 trailing

What is the best way to get rid of those trailing white spaces?

I was thinking some JS function that goes to the last character that is not a white space, then replace all the white spaces with empty string ?

Any suggestions? If jQuery is better for this I am open to that as well...

Thanks.

+2  A: 
data = data.replace(/\s+$/, "");
  • \s - space
  • + - one or more
Matthew Flaschen
+7  A: 

Here are some useful trimming functions you can use:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}

e.g.

alert("11& 444 DTF# 5676   ".rtrim());
mythz
@mythz: ok let me give these a try...
Tommy
`String.prototype.trim` shouldn't be assigned without checking first if exist, the method is part of the ECMAScript 5 Ed. Standard, and it is already available in a large [number of browsers](http://kangax.github.com/es5-compat-table/). Native implementations are usually way faster than custom made shims.
CMS
A: 

Have you tried using $.trim() ?

Reigel
`$.trim` has no option to remove only trailing whitespace.
Matthew Flaschen
I must have read the problem incorrectly :(
Reigel