Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing only the last whitespace in string - Javascript [duplicate]

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!

like image 348
BeHaa Avatar asked Dec 02 '25 10:12

BeHaa


2 Answers

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");
}
like image 153
Anh Tú Avatar answered Dec 07 '25 16:12

Anh Tú


Try this and let me know if it was helpful.

    var str = "This is it  ";
    alert(str.replace(/(^[\s]+|[\s]+$)/g, ''));
like image 36
A J Avatar answered Dec 07 '25 16:12

A J