13

I have a string like that:

var str = 'aaaaaa, bbbbbb, ccccc, ddddddd, eeeeee ';

My goal is to delete the last space in the string. I would use,

str.split(0,1);

But if there is no space after the last character in the string, this will delete the last character of the string instead.

I would like to use

str.replace("regex",'');

I am beginner in RegEx, any help is appreciated.

Thank you very much.

Community
  • 1
  • 1
Milos Cuculovic
  • 19,631
  • 51
  • 159
  • 265

7 Answers7

38

Do a google search for "javascript trim" and you will find many different solutions.

Here is a simple one:

trimmedstr = str.replace(/\s+$/, '');
Francis Avila
  • 31,233
  • 6
  • 58
  • 96
  • 4
    If you need to delete more than one space `str = str.replace(/\s*$/,"");` https://stackoverflow.com/a/17938206/9161843 – Nafis Jul 30 '20 at 06:36
12

When you need to remove all spaces at the end:

str.replace(/\s*$/,'');

When you need to remove one space at the end:

str.replace(/\s?$/,'');

\s means not only space but space-like characters; for example tab.

If you use jQuery, you can use the trim function also:

str = $.trim(str);

But trim removes spaces not only at the end of the string, at the beginning also.

Igor Chubin
  • 61,765
  • 13
  • 122
  • 144
6

Seems you need a trimRight function. its not available until Javascript 1.8.1. Before that you can use prototyping techniques.

 String.prototype.trimRight=function(){return this.replace(/\s+$/,'');}
 // Now call it on any string.
 var a = "a string ";
 a = a.trimRight();

See more on Trim string in JavaScript? And the compatibility list

Community
  • 1
  • 1
Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
4

You can use this code to remove a single trailing space:

.replace(/ $/, "");

To remove all trailing spaces:

.replace(/ +$/, "");

The $ matches the end of input in normal mode (it matches the end of a line in multiline mode).

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
1

Try the regex ( +)$ since $ in regex matches the end of the string. This will strip all whitespace from the end of the string.

Some programs have a strip function to do the same, I do not believe the stadard Javascript library has this functionality.

Regex Reference Sheet

Scott Stevens
  • 2,546
  • 1
  • 20
  • 29
0

Working example:

   var str  = "Hello World  ";
   var ans = str.replace(/(^[\s]+|[\s]+$)/g, '');

   alert(str.length+" "+ ans.length);
Uooo
  • 6,204
  • 8
  • 36
  • 63
0

Fast forward to 2021,

The trimEnd() function is meant exactly for this!

It will remove all whitespaces (including spaces, tabs, new line characters) from the end of the string.

According to the official docs, it is supported in every major browser. Only IE is unsupported. (And lets be honest, you shouldn't care about IE given that microsoft itself has dropped support for IE in Aug 2021!)

Niket Pathak
  • 6,323
  • 1
  • 39
  • 51