JS 中用 replace 替换字符的问题
"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');