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

作者:半夏时间:2026-10-24 00:49:15浏览:495

本文提供 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>
作者最新文章