3

How can I remove only the last whitespace (if there is any) from the user input? example:

var str = "This is it   ";

How can I remove the last like 1-4 whitespaces but still keep the first 2 whitespace (between this, is and it)

Question solved - thanks a lot!

BeHaa
  • 509
  • 1
  • 6
  • 12
  • Have a look at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/TrimRight – phlogratos Apr 25 '13 at 09:21

3 Answers3

5

Using a function like this:

String.prototype.rtrim = function () {
    return this.replace(/((\s*\S+)*)\s*/, "$1");
}

call:

str.rtrim()

Addition if you like remove all leading space:

String.prototype.ltrim = function () {
    return this.replace(/\s*((\S+\s*)*)/, "$1");
}
Anh Tú
  • 636
  • 7
  • 21
2

Try this and let me know if it was helpful.

    var str = "This is it  ";
    alert(str.replace(/(^[\s]+|[\s]+$)/g, ''));
A J
  • 2,112
  • 15
  • 24
0

you can use jquery trim for that,

var str = "This is it   ";
$.trim(str);
  • .trim() is not support in all browsers, if you want it work, you should write your own function! – Anh Tú Apr 25 '13 at 09:37