0

I have a div with Class name "separator" which holds a URL with different paths, but there is one similarity in each URL. what i did is get the URL from that div and replace a specific parameter.

HTML Code:

<div class="separator">
<a href="http://www.mydomain.com/images/s1600/photo.jpg"><img src="http://www.mydomain.com/images/s1600/photo.jpg" height="225" width="400" /></a>
</div>

Here is the JavaScript Code:

var ImageSource = document.getElementsByClassName('separator')[0].getElementsByTagName('a')[0].href;
ImageSource = ImageSource.replace("0", "0-d");

This code works fine, i only want to target the last 0 from /s1600/ because when this value has 2 Zeros it outputs like this:

http://www.mydomain.com/images/s160-d0/photo.jpg

Which should be

http://www.mydomain.com/images/s1600-d/photo.jpg

Please suggest some solution... Thanks :)

2 Answers 2

1

Replace the 0 followed by a slash.

ImageSource = ImageSource.replace(/0\//, '0-d/')
Sign up to request clarification or add additional context in comments.

Comments

1

You'll probably want a regular expression:

ImageSource = ImageSource.replace(/0(\D*)$/, "0-d$1");

That says "match a 0 followed by a series of non-digit characters through to the end of the string, capturing the non-digit characters, and replace them with 0-d followed by the non-digits".

Details:

  • The 0 is literal (match a 0).
  • The ( and ) define a capture group.
  • The \D means "a non-digit" (so, not 0-9).
  • The * means "zero or more of the previous thing" (in this case, non-digits).
  • The $ means "end of string"

In the replacement string, $1 refers to the text within the capture group.

3 Comments

Not working for me... The Request URL has this value /s1600/ which needs to be changed into this /s1600-d/. This value can be changed into /s1920/, /s800/, i only want to change the LAST 0 to 0-d. the Regex you provided didn't worked :(
Thank you @T.J.Crowder for explaining nicely and clearly :) My problem is solved now
@XeBii: "the Regex you provided didn't worked" Yes, it does: jsbin.com/icavap/1

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.