最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - JavaScript removing trailing white-space and periods from string - Stack Overflow

programmeradmin4浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 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"

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.

发布评论

评论列表(0)

  1. 暂无评论