时间:2021-05-26
[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);
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
复制代码代码如下://计算一个日期字符串与当前日期相差值//输入的参数形式如:2012-12-1212:12:12//返回相差值的字符串functionGetD
本文实例讲述了javascript转换日期字符串为Date日期对象的方法。分享给大家供大家参考。具体如下:这里实现把一个日期字符串如“2014-4-2812:3
字符串转日期、日期转字符串//2014-02-25/***字符串转时间(yyyy-MM-ddHH:mm:ss)*result(分钟)*/stringToDate
split()方法用于把一个字符串分割成字符串数组。例子1在本例中,我们将按照不同的方式来分割字符串:varstr="Howareyoudoingtoday&#
复制代码代码如下://////将日期字符串转换为日期类型//////形如"2012年5月14日"的日期字符串privateDateTimeParseDateTi