Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript and regex: remove space after the last word in a string

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.

like image 507
Milos Cuculovic Avatar asked Jul 03 '12 07:07

Milos Cuculovic


2 Answers

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.

like image 40
Igor Chubin Avatar answered Sep 23 '22 12:09

Igor Chubin


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

Here is a simple one:

trimmedstr = str.replace(/\s+$/, '');
like image 73
Francis Avila Avatar answered Sep 22 '22 12:09

Francis Avila