Reputation: 1733
For example, I have got this image path in my WordPress installation:
baseurl.com/images/02D371FEEA23-150x320px.png
I want to change the 150x320px
value to something like this:
baseurl.com/images/02D371FEEA23-800x600px.png
Note: the 150x320px
can be dynamic!
How can I change that part, while leaving the rest unharmed, in the best practice possible?
Upvotes: 0
Views: 63
Reputation: 2591
Not sure about "best practice," but this should work for almost any url, including urls with dashes:
function replaceImgUrl(original,newWidth,newHeight){
//These 2 lines allow other parts of the url to have a dash
//Divide url
var oldDimensions = original.split("/");
//Get last part
oldDimensions = oldDimensions[oldDimensions.length-1];
//Get old dimensions
oldDimensions = oldDimensions.split("-")[1];
oldDimensions = oldDimensions.split("px")[0];
oldDimensions = oldDimensions.split("x");
//oldDimensions has been figured out!
var ret = "";
for(var i = 0; i < original.split("/").length-1; i++)
{
ret += original.split("/")[i];
ret += "/";
}
return ret+original.split("/")[original.split("/").length-1].replace(oldDimensions[0],newWidth).replace(oldDimensions[1],newHeight);
}
console.log(replaceImgUrl("baseurl.com/images/02D371FEEA23-150x320px.png",546,23789));
Upvotes: 0
Reputation: 19007
You can use Regex and get it done.
Below is an example.
var string = "baseurl.com/images/02D371FEEA23-150x320px.png";
var changedString = string.replace(/(-)\d+x\d+/g,"$1800x600");
console.log(changedString);
Explaining the Regex: (-)\d+x\d+
(
)
are to capture this part of the string for later use during replace.\d
digit +
any number followed by a x
followed by a digit \d
any number +
.During replace I make sure the captured hyphen is retained. The captured string is stored in $1
.
Upvotes: 1
Reputation: 2317
<script>
var str = 'DSCN0551-130x130.jpg';
alert(str);
var matches = str.replace(/(\d+)x(\d+)\.(\w+)$/,"800px X 750px");
alert(matches);
</script>
Upvotes: 2
Reputation: 43557
Assuming URL structure is always the same, use regex /-\d+x\d+px\./
to replace required string.
function replaceText() {
var value = document.getElementById('inp').value;
alert(
value.replace(/-\d+x\d+px\./, '-800x600px.')
);
}
replaceText();
<input type="text" value="baseurl.com/images/02D371FEEA23-150x320px.png" onChange="replaceText()" id="inp"/>
Upvotes: 3