栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

js 日期字符串截取分割成单个具体的日期(2009-12-30 13:28:29)

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

js 日期字符串截取分割成单个具体的日期(2009-12-30 13:28:29)


[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]
下面是用数组+正则替换实现的代码

[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]
"hand hand hand"想变换为"hand.gif hand.gif hand.gif"
开始用
str=str.replace("hand","hand.gif");
输出:hand.gif hand hand
只替换了一次。。。:(
想到用正则,因为replace本来就可以用正则替换。

引用
返回根据正则表达式进行文字替换后的字符串的复制。

stringObj.replace(rgExp, replaceText)


于是写
str = str.replace(/hand/,"hand.gif")
无效。。。
全部替换要加g,
str = str.replace(/hand/g,"hand.gif")
还是不行:(

参考了Javascript的replace方法与正则表达式结合应用讲解这篇文章后,终于明白,原来要用()括起来,才会替换()里的东东。正确的写法如下:
str = "hand hand hand";
str=str.replace(/(hand)/g,"hand.gif");
document.write(str);
正确输出:hand.gif hand.gif hand.gif。

JS的正则另一种写法是使用RegExp:
如str=str.replace(/(hand)/g,"hand.gif");
等同于:
reg = new RegExp("(hand)","g");
str = str.replace(reg,'hand.gif');
reg需要动态生成时更适合使用这种方式。

扩展一下:
str = "hand'( hand'( hand'(";
str=str.replace(/(hand'()/g,"hand.gif");
document.write(str);

str = 'hand'( hand'( hand'(';
str=str.replace(/(hand'()/g,"hand.gif");
document.write(str);
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/117101.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号