0

I'm trying to replace a part of the url with another string in javascript, so for example i have the following:

res/icons/android/quickshop/icon-36-ldpi.png
res/icons/android/quickshop/icon-48-mdpi.png
res/icons/ios/quickshop/icon-72-hdpi.png
res/icons/ios/quickshop/icon-96-xhdpi.png

and I want to replace it to the following (quickshop is dynamic and can be any series of characters, mostly [a-z][A-Z])

res/icons/android/homecenter/icon-36-ldpi.png
res/icons/android/homecenter/icon-48-mdpi.png
res/icons/ios/homecenter/icon-72-hdpi.png
res/icons/ios/homecenter/icon-96-xhdpi.png

I was always very lousy when it comes to regular expressions, anyone could help?

8
  • @Shafizadeh yup one string per line, i thought i would put 4 examples to illustrate Commented Apr 15, 2016 at 21:51
  • Ok, what language are you using? Commented Apr 15, 2016 at 21:52
  • @Shafizadeh Javascript Commented Apr 15, 2016 at 21:52
  • @Shafizadeh updated the question to clarify it a bit Commented Apr 15, 2016 at 21:54
  • I'm not sure I get you right, do you want something like this: regex101.com/r/pF1nY9/3 Commented Apr 15, 2016 at 21:57

2 Answers 2

2

Try this:

/(([\w]+\/){3})([^\/]+)(\/.+)/gm

Regex101 Demo


var re = /(([\w]+\/){3})([^\/]+)(\/.+)/gm; 
var str = 'res/icons/android/quickshop/icon-36-ldpi.png';
var replaceWord = 'homecenter'
var subst = '$1' + replaceWord + '$4';

var result = str.replace(re, subst);
// show result
window.alert(result);

could even be written as a function:

function replaceURL(url, strReplace){
    let re = /(([\w]+\/){3})([^\/]+)(\/.+)/gm; 
    var subst = '$1' + strReplace + '$4';
    return url.replace(re, subst);
}

var originalURL = 'res/icons/android/quickshop/icon-36-ldpi.png';
var replaceWord = 'homepage';

var newURL = replaceURL(originalURL, replaceWord);

document.write(newURL);

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

2 Comments

used the wrong references - see above (changed \1 to $1 etc)
All those URLs are one string per line.
1

Try this:

var str    = "res/icons/android/quickshop/icon-36-ldpi.png\nres/icons/android/quickshop/icon-48-mdpi.png\nres/icons/ios/quickshop/icon-72-hdpi.png\nres/icons/ios/quickshop/icon-96-xhdpi.png",
    result = str.replace(/([\w.-]+)(\/[\w.-]+)$/gm,"homecenter$2");
console.log(result);
alert(result);

Comments

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.