Javascript 如何从字符串中删除最后一个和第一个空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10811896/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:02:48  来源:igfitidea点击:

How to remove last and first spaces from a string?

javascript

提问by xRobot

Possible Duplicate:
How do I trim a string in javascript?

可能的重复:
如何在 javascript 中修剪字符串?

I need to remove only the last and the first spaces from a generic string.

我只需要从通用字符串中删除最后一个和第一个空格。

Example:

例子:

var str = " hello world "; // become "hello world"
var str = "ehi, do you come from ? "; // become "ehi, do you come from ?"
var str = "I am from Cina"; // remain "I am from Cina"

How can I do that ?

我怎样才能做到这一点 ?

回答by papaiatis

The trim from jQueryis what you are looking for.

来自 jQuery修剪正是您正在寻找的。

$.trim(' string with spaces at the ends ');

$.trim(' string with spaces at the ends ');

Or plain javascript:

或者普通的javascript:

' string with spaces at the ends '.trim()

' string with spaces at the ends '.trim()