使用javascript删除不需要的空格
在我的应用程序中,我想从开头和结尾删除不需要的空格。而且,如果单词之间的空格超过一个,也要删除它们,只留下一个空格。使用javascript删除不需要的空格,javascript,trim,Javascript,Trim,在我的应用程序中,我想从开头和结尾删除不需要的空格。而且,如果单词之间的空格超过一个,也要删除它们,只留下一个空格。 如何执行此操作?此操作可以删除前导空格和尾随空格,并将两个或更多空格减少为单个空格: str.replace(/^\s+|\s+$/, '').replace('/\s\s+/', ' ') 试试这个: //remove leading spaces content = content.replace(/^\s+/g,''); //remove trailing spaces
如何执行此操作?此操作可以删除前导空格和尾随空格,并将两个或更多空格减少为单个空格:
str.replace(/^\s+|\s+$/, '').replace('/\s\s+/', ' ')
试试这个:
//remove leading spaces
content = content.replace(/^\s+/g,'');
//remove trailing spaces
content = content.replace(/\s+$/g,'');
//remove whitespaces in the middle
content = content.replace(/\s+/g,' ');
您可以使用jQuery trim方法。此函数从输入字符串中删除所有新行和所有前导或尾随空格
var str = ' it is a test string ';
alert($.trim(str));
当我使用此选项时,可能会出现重复的错误“x.rep未定义”x是我的变量,仅删除前导的一个