1

Is it possible to replicate this with javascript?

preg_replace('/(.gif|.jpg|.png)/', '_thumb$1', $f['logo']);

EDIT - I am not getting this following error for this peice of code,

unterminated string literal

$('#feed').prepend('<div class="feed-item"><img src="'+html.logo.replace(/(.gif|.jpg|.png)/g, "_thumb$1")+'"/> <div class="content">'+html.content+'</div></div>').fadeIn('slow');

3
  • 3
    By replication do mean that you want the same errors that the original code has? Commented Jan 28, 2011 at 21:04
  • 2
    @Mark: I was just going to say... what about them . ? Commented Jan 28, 2011 at 21:05
  • To be strictly correct you should use \.jpe?g in both. The short jpg variant is just a concession to the DOS era. Commented Jan 28, 2011 at 21:12

3 Answers 3

6

There are a couple of problems with the code you are trying to replicate:

  • It matches "extensions" even if they aren't at the end of the filename.
  • The dot in a regular expression matches (nearly*) any character, not just a period.

Try this instead:

'abc.jpg'.replace(/\.(jpg|gif|png)$/, '_thumbs$&')

I'm assuming that the string you are trying to replace contains only a single filename.


*See the documentation for PCRE_DOTALL.

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

2 Comments

Would be even nicer if you dropped the outer capturing group and used $&. +1
@nikic: +1 Nice, thanks! I completely forgot you can do that in Javascript. :)
3

Yes, except that in JavaScript, replace is a string's method, so it would be rearranged a little (also, the array/object notation is slightly different):

f.logo.replace(/\.(gif|jpg|png)/, '_thumb.$1');

more info

6 Comments

@nikic When would an image's filename include a period and the extension more than once?
@sdleihssirhc: Damned, you are obviously right. I always make the mistake of forgetting that modifier and now I see that mistake even if it isn't a mistake... +1 for pointing out.
It's not completely impossible that a filename contains two extensions. It would be retarded, yes. But it's technically allowed and HTTP content negotiation schemes could indeed use a redundant img0011.pnga.en.png. Thus I would also avoid the $ anchor but append \b instead.
@sdleihssirhc - Happens all the time in windows "file.gif.txt.jpg". Technically your missing the $ anchor.
@mario By avoiding the $, do you mean end of string or the $1 that I used?
|
0
somestringvar.replace(/(.gif|.jpg|.png)/, replacementValue)

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.