最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get string piece after last symbols "" or "" - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 11

You 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]; 
发布评论

评论列表(0)

  1. 暂无评论