0

i would like to replace the css background urls like these:

body {
  background: url("../common/images/nyau.jpg") center center;
}
.alma { 
  background: url("./vau/vau.jpg"); 
}
.ata { 
  background: url("./mak.jpg"); 
}

to these:

body {
  background: url("./images/nyau.jpg") center center;
}
.alma { 
  background: url("./images/vau.jpg"); 
}
.ata { 
  background: url("./images/mak.jpg"); 
}

Unfortunately i am not familiar with regex at all.

I know i can select ("../common/images/nyau.jpg") this part with /\((.*?)\)/g but i need to capture the part from the last / (nyau.jpg) somehow. So i could do ./images/$1 or something like that.

EDIT: in the api of gulp-replace i am only allowed to use regular expressions without any javascript function.

4
  • 2
    What is purpose of separate lines for each background property ? Last background set would overwrite previous two Commented Jan 10, 2016 at 17:44
  • 1
    bg = './images/' + bg.split('/').pop() Commented Jan 10, 2016 at 17:46
  • @adeneo we both had the same idea Commented Jan 10, 2016 at 17:48
  • You are right, maybe i shouldn't have come up with such a silly example. But in this case it is not important. Commented Jan 10, 2016 at 17:48

1 Answer 1

1

This function fixPath(path) will return you the path as you want it to have, you can then apply it whereever you need to fix you backgrounds.

function fixPath(path) {
  return path.replace(/(.*\/)(.*)$/, "./images/$2")
  //  return "./images/" + path.split("/").pop()
}

// Demo Paths
var paths = ["../common/images/nyau.jpg", "./vau/vau.jpg", "./mak.jpg"]

// Do it for all paths
paths = paths.map(fixPath)

// Demo Output
document.write(JSON.stringify(paths))

Sign up to request clarification or add additional context in comments.

6 Comments

unfortunately i can only use regex and no javascript functions
@AttilaEgyed whs is that? But OK, i'll find the regex
@CodeSir check regexr.com, i use gulp-replace and in that api i am only allowed to use regular expressions without any javascript function
@AttilaEgyed I added the RegEx
@CodeSir nice! But this will also replace all regular urls like this http://regexr.com/foo.html?q=bar for example. The best would be to make some constraint to only look for the contents between url(...)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.