可能重复:
在JavaScript中从字符串中删除空格
我使用了trim函数来删除句子开头和结尾的空格.如果句子中的单词之间有很多空格,是否有任何方法可以修剪?
例如
"abc def. fds sdff."
Run Code Online (Sandbox Code Playgroud)
Koo*_*Inc 40
try
"abc def. fds sdff."
.replace(/\s+/g,' ')
Run Code Online (Sandbox Code Playgroud)
or
"abc def. fds sdff."
.split(/\s+/)
.join(' ');
Run Code Online (Sandbox Code Playgroud)
or use this allTrim String extension
String.prototype.allTrim = String.prototype.allTrim ||
function(){
return this.replace(/\s+/g,' ')
.replace(/^\s+|\s+$/,'');
};
//usage:
alert(' too much whitespace here right? '.allTrim());
//=> "too much whitespace here right?"
Run Code Online (Sandbox Code Playgroud)
She*_*hef 26
var str = 'asdads adasd adsd';
str = str.replace(/\s+/g, ' ');
Run Code Online (Sandbox Code Playgroud)
您可以使用此Javascript将多个连续的空格缩减为一个空格:
var str = "abc def. fds sdff.";
str = str.replace(/\s+/g, " ");
Run Code Online (Sandbox Code Playgroud)
如果您的意思不是多个连续空格,请在问题中阐明您的意思。
| 归档时间: |
|
| 查看次数: |
24840 次 |
| 最近记录: |