Javascript and regex: remove space after last word in line

I have a line like this:

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

My goal is to remove the last space in the line. I would like to use

 str.split(0,1); 

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

I would like to use

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

I am new to RegEx, any help is appreciated.

Thank you very much.

+4
source share
6 answers

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

Here is a simple one:

 trimmedstr = str.replace(/\s+$/, ''); 
+13
source

When you need to remove all spaces at the end:

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

When you need to delete one place at the end:

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

\s means not only space, but also space-like characters; e.g. tab.

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

 str = $.trim(str); 

But trim removes spaces not only at the end of a line, but also at the beginning.

+4
source

It seems you need a trimRight function. Its not available until Javascript 1.8.1. Prior to this, you can use prototyping methods.

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

Read more on Trimming String in JavaScript? And compatibility list

+4
source

You can use this code to remove one trailing space:

 .replace(/ $/, ""); 

To remove all trailing spaces:

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

$ corresponds to the end of input in normal mode (it corresponds to the end of a line in multi-line mode).

+3
source

Try the regex ( +)$ , since $ in regex matches the end of the line. This will separate all spaces from the end of the line.

Some programs have a strip function to do the same, I don't believe the standard Javascript library has this functionality.

Regex Reference Sheet

+1
source

Working example:

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

All Articles