3

I am attempting to remove all trailing white-space and periods from a string so that if I took either of the following examples:

var string = "  ..  bob is a string .";

or

var string = " .  bob is a string . ..";

They would end up as:

"bob is a string"

I know diddly squat about regex but I found a function to remove trailing white-space here:

str.replace(/^\s+|\s+$/g, "");

I tried modifying to include periods however it still only removes trailing white-space characters:

str.replace(/^[\s+\.]|[\s+\.]$/g, "");

Can anyone tell me how this is done and perhaps explain the regular expression used to me?

Community
  • 1
  • 1
George Reith
  • 13,132
  • 18
  • 79
  • 148

2 Answers2

5

Your regex is almost right, you just need to put the quantifier (+) outside of the character class ([]):

var str = " .  bob is a string . ..";
str.replace(/^[.\s]+|[.\s]+$/g, "");
//"bob is a string"
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • Thanks, why do you not need to escape the `.` character as I read `.` matches almost any character? – George Reith Sep 07 '12 at 11:38
  • @GeorgeReith because the `.` is inside character class, so it means literally a `.`. Outside character class you would need to escape it. Just like the `+` you have in your regex doesn't mean a quantifier because it's inside a character class, otherwise you would have had to escape the `+` as well. Inside character class, you only need to escape characters special to character class, such as `]`, `^`, `-`, and backslash. – Esailija Sep 07 '12 at 11:38
0

Try this:

var str = " .  bob is a string . ..";
var stripped = str.replace(/^[\s.]+|[\s.]+$/g,"");

Within character classes ([]) the . need not be escaped. This will remove any leading or trailing whitespaces and periods.

Mithrandir
  • 24,869
  • 6
  • 50
  • 66