Reputation: 623
I've got this string (from the end of a css background-image url):
.jpg")
I want to remove the quote-mark and close-parenthesis:
var ext = str.replace(/"\)/, '');
In Firefox I get
.jpg
as expected. In Safari and Chrome I get
.jpg)
Not sure why they're different, but what I do know is that Firefox adds quotes around the url of the background-image whether I use them or not. ie
background-image: url(../img/before_after/slides/Brittany_487_a.jpg)
returns with quotes around the url in Firefox, but not in WebKit browsers.
Upvotes: 0
Views: 801
Reputation: 371
It's probably not really the RegExp that's different, but rather (as you pointed out yourself) Firefox adds quotes around the url, while Safari and Chrome does not.
Hence in Firefox you get:
.jpg")
which is matched by your RegExp, but in Safari and Chrome, you get:
.jpg)
which does not matched by your RegExp.
Try changing your RegExp to cover both scenarios, like this:
var ext = str.replace(/"?\)/, '');
EXTRA: Also worth nothing, that in case the file-name happens to contain ") or ) you will not get the expected result. If you know, that the string you're trying to remove is going to be at the end, then you can fix it by using $ which will match only the end of your subject string:
var ext = str.replace(/"?\)$/, '');
Even further, if you want to cover cases where a single quote '
is used instead of the double qoute "
you could do that by listing all the valid characters in brackets: []
, so in this case it would be: ["']
, so the whole RegExp:
var ext = str.replace(/['"]?\)$/, '');
Upvotes: 3
Reputation: 50905
In the case that the "
isn't automatically inserted, you can make it optional in the match. Try the regex:
.replace(/("|')?\)$/, "");
DEMO: http://jsfiddle.net/R4hfF/
The ?
says "0 or 1 occurrences of the previous character/group".
The "|'
is in case the quote is single or double.
The $
says this will occur at the end of the string. If you have the whole line, a ";" might be there (like a normal CSS rule), so you could put ;
right before the $
.
Upvotes: 4
Reputation: 4877
You can make a character optional by adding ?
after it. So if the quote is only there in some browsers you can change your pattern to /"?\)/
.
Upvotes: 1