javascript - 删除空格但在文本区域中保留换行符 JS 或 jQuery

标签 javascript jquery textarea whitespace extra

我想删除行首和行尾的多余空格,但保留换行符,这就是我的尝试。

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”

最佳答案

您的代码肯定会删除所有空格。

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;
}

希望这有帮助! :)

关于javascript - 删除空格但在文本区域中保留换行符 JS 或 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37956912/

相关文章:

javascript - Ajax 将数组保存到全局变量中不起作用,一直未定义

javascript - 在 php 和 javascript 中获取不同的 unix 时间戳(服务器时间错误)

c# - 单击 ASP.net 时对数据库的 jQuery Ajax 调用

php - 将文本区域的内容转换为数组

javascript - Titanium - ScrollView 中的文本区域

javascript - 如何在文本区域中选择文本行

javascript - Google Charts 线条粗细(和清晰度)不同

javascript - 如何在angularjs中获取复选框值和单选值

javascript - Jquery表单与recaptcha序列化问题?

javascript - 检查元素是否为 div