views:

135

answers:

5

I'm having a lot of difficulty matching an image url with spaces.

I need to make this

http://site.com/site.com/files/images/img 2 (5).jpg

into a div like this:

.replace(/(http:\/\/([^\s]+\.(jpg|png|gif)))/ig, "<div style=\"background: url($1)\"></div>")

Here's the thread about that: http://stackoverflow.com/questions/1066697/regex-matching-image-url-with-spaces

Now I've decided to first make the spaces into entities so that the above regex will work.

But I'm really having a lot of difficulty doing so. Something like this:

.replace(/http:\/\/(.*)\/([^\<\>?:;]*?) ([^\<\>?:;]*)(\.(jpe?g|png|gif))/ig, "http://$1/$2%20$3$4")

Replaces one space, but all the rest are still spaces.

I need to write a regex that says, make all spaces between http:// and an image extension (png|jpg|gif) into %20.

At this point, frankly not sure if it's even possible. Any help is appreciated, thanks.

Trying Paolo's escape:

.escape(/http:\/\/(.*)\/([^\<\>?:;]*?) ([^\<\>?:;]*)(\.(jpe?g|png|gif))/)

Another way I can do this is to escape serverside in PHP, and in PHP I can directly mess with the file name without having to match it in regex.

But as far as I know something like htmlentities do not apply to spaces. Any hints in this direction would be great as well.

+4  A: 

Try the escape function:

>>> escape("test you");
test%20you
Paolo Bergantino
Hi, can you give an example? I edited my post with my non-working attempt.
Mark
A: 

Lets say you have the string variable urlWithSpaces which is set to a URL which contains spaces.

Simply go:

urlWithoutSpaces = escape(urlWithSpaces);
Lachlan McDonald
The issue is, by the time I get to do something with client side, the url will be part of a post that the user submitted, so I would have to match it first.
Mark
A: 

If you want to control the replacement character but don't want to use a regular expression, a simple...

$destName = str_replace(' ', '-', $sourceName);

..would probably be the more efficient solution.

middaparka
This is what worked for me, thanks.though I replaced it with %20.
Mark
A: 

What about urlencode() - that may do what you want.

Meep3D
Oh, and rawurlencode () may be more appropriate with the space encodings.
Meep3D
Oh, it's PHP too.
Meep3D
Thanks a lot, though that encodes too much. When '/' becomes %2F the url refuses to work.
Mark
A: 

On the JS side you should be using encodeURI(), and escape() only as a fallback. The reason to use encodeURI() is that it uses UTF-8 for encoding, while escape() uses ISO Latin. Same problems applies for decoding.

encodeURI = encodeURI || escape;

alert(encodeURI('image name.png'));
Ionuț G. Stan