我想删除行首和行尾的多余空格,但保留换行符,这是我尝试过的。
function removeSpaces(string) {
return string.split(' ').join('');
}<center>
<form action="getid.php" method="post">
<textarea name="items" id="itemNames" cols="100" rows="10" onblur="this.value=removeSpaces(this.value);"></textarea><br />
<input type="submit" value="Get dem IDs">
<input type="button" id="remove" value="Remove extra spaces">
</form>
</center>
但是,它删除了所有的空格和'\n‘
发布于 2016-06-22 09:53:11
你的代码肯定会删除所有的空格。
string.split(' ')通过空格拆分整个字符串,其中包括字符串本身之前、之后和内部的空格。
我的方法如下:
function removeSpaces(string) {
// Remove leading spaces
while(string.indexOf(' ') === 0) {
string = string.substr(1);
}
// Remove trailing spaces
while(string[string.length-1] === ' ') {
string = string.substr(0, string.length-1);
}
return string;
}希望这能有所帮助!:)
发布于 2016-06-22 11:20:48
function removeSpaces(string) {
// Remove line breaks
var str = string.replace(/\n/g,"");
return str.split(' ').join('');
}发布于 2016-06-22 13:17:32
只需使用.trim()即可
function removeSpaces(string) {
return string.trim();
}https://stackoverflow.com/questions/37956912
复制相似问题