-1

String contents :

background:url(abcd.gif); background:url(images/header2.gif) no-repeat;
background:url(images/bullet1.gif) no-repeat 11px 13px;

Javascript Code :

var testRE = originalcode.match("url\(\(.*)\)"); 
testRE = testRE[2].replace('(',''); 
testRE = testRE.split(')')[0]; 
var img_path = "http://xyz.com/800002418/"+testRE; 
originalcode = originalcode.replace(testRE,img_path);

In the above code it's only replacing first instance of match. I am trying to replace multiple instances for url in string like above are 3 instances in string for url. But it's only replacing 1st instance and that is "abcd.gif" to "http://xyz.com/800002418/abcd.gif". And rest is as it is.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Mangesh Narayankar
  • 591
  • 2
  • 5
  • 5

2 Answers2

1

I suspect what you're actually trying to do here is as follows:

originalcode = originalcode.replace(/url\(([^\)]*)\)/g, "url(http://xyz.com/800002418/$1)");
Phylogenesis
  • 7,775
  • 19
  • 27
  • Thanks alot man, it's woring. – Mangesh Narayankar Jun 25 '13 at 13:53
  • Hey, i am trying to replace like originalcode = originalcode.replace(/url\(([^\)]*)\)/g, "url(/800002418/$1)"); means instead of "http://xyz.com/" if i put "" then it's replacing like "". This means creating opening and closing tags. How can i stick output with "". – Mangesh Narayankar Jun 25 '13 at 14:16
0

See @Phylogenesis's answer for how to do what you seem to think you want to do, but is that what you really want to do? After you've modified the string, what are you going to do with it? I suppose perhaps you're going to set it as the string CSS value on some element, as in elt.cssText=. But why do you think three background properties in a row are going to do anything useful? Each one will just override the previous one.

Taking a step back, instead of trying to manipulate CSS declarations as strings using regexp's, I suggest manipulating individual property values. So, something like

foo.style.backgroundImage=foo.style.backgroundImage
    .replace(/\(.*)\)/,"http://..."+$1);

But I'm still confused as to why you would want to do this. I guess it's because the remote URL is only known at run-time? The most flexible solution is to place a CSS file on the host in question and load it. If the images are there, you ought to be able to arrange to put a CSS file there along with them. The URL references in the background property values will then automatically be interpreted in terms of the URL of the CSS file, without having to rewrite in this ugly fashion.