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?
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?
Share Improve this question edited May 23, 2017 at 10:34 CommunityBot 11 silver badge asked Sep 7, 2012 at 11:25 George ReithGeorge Reith 13.5k18 gold badges81 silver badges151 bronze badges2 Answers
Reset to default 6Your 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"
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.