[英]JavaScript removing trailing white-space and periods from string
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 : 我知道diddly蹲
regex
,但我发现一个函数来删除尾随空白这里 :
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? 谁能告诉我这是怎么做的,也许可以解释一下我用过的正则表达式?
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.
这将删除任何前导或尾随空格和句点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.