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?

2 Answers 2

6

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"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, why do you not need to escape the . character as I read . matches almost any character?
@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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.