JavaScript 实现 trim、ltrim 和 rtrim 去空格函数

作者:半夏

时间:2026-10-24

浏览:494

本文提供 JavaScript 中用于去除字符串空格的三个核心函数:trim(去除两端空格)、ltrim(去除左侧空格)和 rtrim(去除右侧空格)。通过正则表达式 /^\s*/ 和 /\s*$/ 配合 replace 方法,实现高效的字符串清洗功能,适用于前端表单数据处理等场景。

文章目录
<input type="text" name="mytxt" value=" 12345678 " /> <input type="button" name="cmd1" onclick="mytxt2.value=mytxt.value.trim()" value="去两边的空格"/> <input type="text" name="mytxt2"/> <input type="button" name="cmd1" onclick="mytxt3.value=mytxt.value.ltrim()" value="去左边的空格"/> <input type="text" name="mytxt3"/> <input type="button" name="cmd1" onclick="mytxt4.value=mytxt.value.rtrim()" value="去右边的空格"/> <input type="text" name="mytxt4"/>  

注意:若引入外部 JavaScript 文件,需刷新页面后方可执行。


JavaScript 去空格函数实现代码

将去空格逻辑封装为函数,实现方式如下:


具体代码实现如下:

<script type="text/javascript">
function trim(str){ //删除左右两端的空格
return str.replace(/(^\s*)|(\s*$)/g, "");
} 
function ltrim(str){ //删除左边的空格
return str.replace(/(^\s*)/g,"");
} 
function rtrim(str){ //删除右边的空格
return str.replace(/(\s*$)/g,"");
} 
</script>

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章