I need get from string, piece after last \
or /
, that is from this string C:\fake\path\some.jpg
result must be some.jpg
I tried this:
var str = "C:\fake\path\some.jpg";
var newstr = str.replace(/[^\\\/]+$/, "");
alert(newstr);
/
but not works, what is right regex for this?
I need get from string, piece after last \
or /
, that is from this string C:\fake\path\some.jpg
result must be some.jpg
I tried this:
var str = "C:\fake\path\some.jpg";
var newstr = str.replace(/[^\\\/]+$/, "");
alert(newstr);
http://jsfiddle/J4GdN/3/
but not works, what is right regex for this?
Share Improve this question edited May 1, 2013 at 13:57 George 36.8k9 gold badges69 silver badges109 bronze badges asked May 1, 2013 at 13:55 Oto ShavadzeOto Shavadze 42.9k55 gold badges165 silver badges246 bronze badges 1-
4
Well your str needs to be
var str = "C:\\fake\\path\\some.jpg";
– epascarello Commented May 1, 2013 at 13:59
3 Answers
Reset to default 11You don't need a regex to do it, this should work:
var newstr = str.substring(Math.max(str.lastIndexOf("\\"), str.lastIndexOf("/")) + 1);
Well your str needs to be escaped \\
for it to work correctly. You also need to use match since the reg exp you are using is matching the end, not the start.
var str = "C:\\fake\\p\ath\some.jpg";
var newstr = str.match(/[^\\/]+$/);
alert(newstr);
JSFiddle
first, let's escape the backslashes
var str = "C:\\fake\\path\\some.jpg";
var newstr = str.replace(/[^\\\/]+$/, "");
alert(newstr);
now, you are removing some.jpg
instead of getting it as the result.
here are a few options to fix this:
1.replace with a regex
var newstr = str.replace(/.*[\\\/]/, "");
2.split with regex (doesn't work in all browsers)
var tmp = str.split(/\\|\//);
var newstr = tmp[tmp.length-1];
4.as said here, match
var newstr = str.match(/.*[\\\/](.*)/)[1];