删除前尾空格[重复]

时间:2021-11-11 00:13:41

This question already has an answer here:

这个问题已经有了答案:

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?

我想要移除字符串末尾的额外空间,但它会移除字符串中的每一个空间,所以我怎么才能移除最后的额外空间,并保留金色的,毫不畏惧的黎明呢?

2 个解决方案

#1


7  

try doing

试着做

trimmedstr = str.replace(/\s+$/, '');

or maybe

或者

.replace(/ +$/, "");

#2


21  

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.

对于这种情况,可以使用string .trim()。它从字符串中删除前导和后导空格。正则表达式str.replace(/ ^ \ s + | \ s + $ / g”)也将会做同样的事情。

#1


7  

try doing

试着做

trimmedstr = str.replace(/\s+$/, '');

or maybe

或者

.replace(/ +$/, "");

#2


21  

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.

对于这种情况,可以使用string .trim()。它从字符串中删除前导和后导空格。正则表达式str.replace(/ ^ \ s + | \ s + $ / g”)也将会做同样的事情。