JavaScript 删除前导和尾随空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17769753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript remove leading and trailing spaces
提问by wateraura
Here is a test:
这是一个测试:
console.log(" Golden Katana of the Unflinching Dawn ".replace(/\s+/g,""))
I want to remove the extra spaces at the end of the string but it removes every space in the string, so how could I remove just the extra spaces at the end and just keep Golden Katana of the Unflinching Dawn
?
我想删除字符串末尾的多余空格,但它删除了字符串中的每个空格,那么我怎么能只删除末尾的多余空格而只保留Golden Katana of the Unflinching Dawn
?
采纳答案by No Idea For Name
try doing
尝试做
trimmedstr = str.replace(/\s+$/, '');
or maybe
或许
.replace(/ +$/, "");
回答by hexacyanide
You can use str.trim()
for this case. It removes the leading and trailing whitespace from a string. The regular expression str.replace(/^\s+|\s+$/g,'')
will alternatively do the same thing.
您可以str.trim()
用于这种情况。它从字符串中删除前导和尾随空格。正则表达式str.replace(/^\s+|\s+$/g,'')
也可以做同样的事情。