Javascript replace not working [duplicate]
I'm working on javascript and I have some problem with javascript replace function. Here is my code:
var jpgPath ="../Publish/Pdf/Publish_27Jul2011_04-47-09_PM/adfm201000135.jpg@../Publish
/Pdf/Publish_27Jul2011_04-47-09_PM/adfm2010001352.jpg@../Publish
/Pdf/Publish_27Jul2011_04-47-09_PM/adfm2010001353.jpg@../Publish
/Pdf/Publish_27Jul2011_04-47-09_PM/adfm2010001354.jpg@../Publish
/Pdf/Publish_27Jul2011_04-47-09_PM/adfm2010001355.jpg@../Publish
/Pdf/Publish_27Jul2011_04-47-09_PM/adfm2010001356.jpg@../Publish
/Pdf/Publish_27Jul2011_04-47-09_PM/adfm2010001357.jpg@../Publish
/Pdf/Publish_27Jul2011_04-47-09_PM/adfm2010001358.jpg@../Publish
/Pdf/Publish_27Jul2011_04-47-09_PM/adfm2010001359.jpg@../Publish
/Pdf/Publish_27Jul2011_04-47-09_PM/adfm20100013510.jpg@../Publish
/Pdf/Publish_27Jul2011_04-47-09_PM/adfm20100013511.jpg@../Publish
/Pdf/Publish_27Jul2011_04-47-09_PM/adfm20100013512.jpg";
jpgPath = jpgPath.replace("..", "../..");
but it's not replacing all the occurrence of ".." with "../..", it's replacing the first match and after that it ignore other matches.
Pass a regex with global flag as first param
jpgPath = jpgPath.replace(/\.\./g, "../..");
Try following:
jpgPath = jpgPath.replace(/../g, ”../..”);
Run jpgPath = jpgPath.replace(/\.\./g, "../..");
instead.
To do that, you'll need to use the regex and the g
(global) operator:
// because . is a special character in regex, you need to escape it
jpgPath = jpgPath.replace(/\.\./g, "../..");
Try this.
var jpgPath ="../Publish/Pdf/Publish_27Jul2011_04-47-09_PM/adfm201000135.jpg@../Publish/Pdf/Publish_27Jul2011_04-47-09_PM/adfm2010001352.jpg@../Publish/Pdf/Publish_27Jul2011_04-47-09_PM/adfm2010001353.jpg@../Publish/Pdf/Publish_27Jul2011_04-47-09_PM/adfm2010001354.jpg@../Publish/Pdf/Publish_27Jul2011_04-47-09_PM/adfm2010001355.jpg@../Publish/Pdf/Publish_27Jul2011_04-47-09_PM/adfm2010001356.jpg@../Publish/Pdf/Publish_27Jul2011_04-47-09_PM/adfm2010001357.jpg@../Publish/Pdf/Publish_27Jul2011_04-47-09_PM/adfm2010001358.jpg@../Publish/Pdf/Publish_27Jul2011_04-47-09_PM/adfm2010001359.jpg@../Publish/Pdf/Publish_27Jul2011_04-47-09_PM/adfm20100013510.jpg@../Publish/Pdf/Publish_27Jul2011_04-47-09_PM/adfm20100013511.jpg@../Publish/Pdf/Publish_27Jul2011_04-47-09_PM/adfm20100013512.jpg";
jpgPath = jpgPath.replace(/\.\./g, "../..");
console.log(jpgPath );
http://jsfiddle.net/t8Wp8/
精彩评论