知识大全 JavaScript去除空格的三种方法
Posted 知
篇首语:生活的理想,就是为了理想的生活本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 JavaScript去除空格的三种方法相关的知识,希望对你有一定的参考价值。
JavaScript去除空格的三种方法 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!
方法一:最好的方法 采用的是正则表达式 这是最核心的原理 其次 这个方法使用了JavaScript的prototype 属性
其实你不使用这个属性一样可以用函数实现 但这样做后用起来比较方便 下面就来看看这个属性是怎么来用的
引用内容
返回对象类型原型的引用
objectName prototypeobjectName 参数是对象的名称
说明用 prototype 属性提供对象的类的一组基本功能 对象的新实例 继承 赋予该对象原型的操作
例如 要为 Array 对象添加返回数组中最大元素值的方法 要完成这一点 声明该函数 将它加入 Array prototype 并使用它
function array_max( )var i max = this[ ];for (i = ; i < this length; i++)if (max < this[i])max = this[i];return max;Array prototype max = array_max;var x = new Array( );var y = x max( );
该代码执行后 y 保存数组 x 中的最大值 或说
所有 JScript 内部对象都有只读的 prototype 属性 可以象该例中那样为原型添加功能 但该对象不能被赋予不同的原型 然而 用户定义的对象可以被赋给新的原型
本语言参考中每个内部对象的方法和属性列表指出哪些是对象原型的部分 哪些不是
下面是代码原文
程序代码
<SCRIPT LANGUAGE= JavaScript ><! //出处:网上搜集// Trim() Ltrim() RTrim()String prototype Trim = function() return this replace(/(^\\s*)|(\\s*$)/g ); String prototype LTrim = function() return this replace(/(^\\s*)/g ); String prototype RTrim = function() return this replace(/(\\s*$)/g ); // ></SCRIPT>
使用方法见以下代码
HTML代码 <SCRIPT LANGUAGE= JavaScript ><! //出处:网上搜集Trim() Ltrim() RTrim()String prototype Trim = function()return this replace(/(^\\s*)|(\\s*$)/g );String prototype LTrim = function()return this replace(/(^\\s*)/g );String prototype RTrim = function()return this replace(/(\\s*$)/g );// ></SCRIPT><input type= text value= 前后都是空格 id= space ><input type= button value= 去前后空格 onclick= javascript:document getElementById( space ) value= /document getElementById( space ) value Trim();document getElementById( space ) select(); ><input type= button value= 去前空格 onclick= javascript:document getElementById( space ) value= /document getElementById( space ) value LTrim();document getElementById( space ) select(); ><input type= button value= 去后空格 onclick= javascript:document getElementById( space ) value= /document getElementById( space ) value RTrim();document getElementById( space ) select(); ><input type= button value= 还原 onclick= javascript:document getElementById( space ) value= 前后都是空格 ; ><a _blank >访问</a> 下面来我们来看看Js脚本中 /s表示什么
引用内容
\\s 匹配任何空白字符 包括空格 制表符 换页符等等 等价于 [ \\f\\n\\r\\t\\v]
请紧记是小写的s
方法二:由于使用方法简单 所以这里就不举例子了
引用内容
//javascript去空格函数 function LTrim(str) //去掉字符串 的头空格var i;for(i= ;i if(str charAt(i)!= &&str charAt(i)!= ) break;str = str substring(i str length);return str;function RTrim(str)var i;for(i=str length ;i>= ;i )if(str charAt(i)!= &&str charAt(i)!= ) break;str = str substring( i+ );return str;function Trim(str)return LTrim(RTrim(str));
方法三:这个方法将函数写在一起 通过传递参数不同而达到不同的实现效果
引用内容
cha138/Article/program/Java/JSP/201311/19273相关参考