Home > Web Front-end > JS Tutorial > body text

js中eval()函数和trim()去掉字符串左右空格应用_javascript技巧

WBOY
Release: 2016-05-16 17:42:26
Original
1502 people have browsed it

对于js中eval()函数的理解和写一个函数trim()去掉字符串左右空格。
trim()是参照了jquery的源码,你可以放心使用。

对于js中eval()函数的理解是本人心得不一定正确。

复制代码 代码如下:




New Document


js中处理字符串过滤前后空格的trim函数是没有的,

而jquery中加入了这个很常用的函数,其源码如下

function trim(t){

return (t||"").replace(/^\s+|\s+$/g, "");

}

有时我们不用jquery,没必要为了一个函数加入整个jquery库,

这时我们可以把源码拷来写个trim函数就行了。



<script> <BR>var f='hello'; <BR>//alert(f); <BR>/* <BR>这里顺便说一下eval()函数,它可以把括号里面的内容当做js脚本计算, <BR>也可以计算数学运算,也可以对字符串计算。 <BR>总之它不是简单的字符串连接函数。 <BR>你可以把它当做js中的js脚本。 <BR>这个和jsp很像,jsp是嵌在html的java代码, <BR>那eval()括号里的内容就是嵌在js中的js代码。 <BR>*/ <BR>//eval("alert('"+f+"')");//计算js脚本,和alert(f)效果一样。 <BR>eval(" var gg='haha'"); <BR>alert(eval("gg"));//eval里的就是嵌入的js代码,等价于var gg='haha',alert(gg); <BR>//alert(eval('3+4'));//计算数学运算,结果7 <BR>//alert(eval('3'+'4'));//计算字符串,结果34 <BR>alert("start"+trim(' abc def ')+"end"); <BR>//jquery中的trim函数,过滤掉首位空格。 <BR>function trim(t){ <BR>return (t||"").replace(/^\s+|\s+$/g, ""); <BR>} <BR></script>
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!