14

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.

2

7 Answers 7

38

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

Here is a simple one:

trimmedstr = str.replace(/\s+$/, '');
Sign up to request clarification or add additional context in comments.

1 Comment

If you need to delete more than one space str = str.replace(/\s*$/,""); stackoverflow.com/a/17938206/9161843
13

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.

Comments

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

Comments

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).

Comments

2

Working example:

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

   alert(str.length+" "+ ans.length);

2 Comments

Doesn't work the way asked in this question. Try str = " Hello World " and the space from beginning will also be removed, resulting str = "Hello World".
str.replace(/\s+$/, '') or str.replace(/\s*$/,'') works perfectly.
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

Comments

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!)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.