Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

javascript - RegEx that will match the last occurrence of dot in a string

I have a filename that can have multiple dots in it and could end with any extension:

tro.lo.lo.lo.lo.lo.png

I need to use a regex to replace the last occurrence of the dot with another string like @2x and then the dot again (very much like a retina image filename) i.e.:

tro.lo.png -> tro.lo@2x.png

Here's what I have so far but it won't match anything...

str = "http://example.com/image.png";
str.replace(/.([^.]*)$/, " @2x.");

any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You do not need a regex for this. String.lastIndexOf will do.

var str = 'tro.lo.lo.lo.lo.lo.zip';
var i = str.lastIndexOf('.');
if (i != -1) {
    str = str.substr(0, i) + "@2x" + str.substr(i);
}

See it in action.

Update: A regex solution, just for the fun of it:

str = str.replace(/.(?=[^.]*$)/, "@2x.");

Matches a literal dot and then asserts ((?=) is positive lookahead) that no other character up to the end of the string is a dot. The replacement should include the one dot that was matched, unless you want to remove it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...