RegEx, which will correspond to the last occurrence of a point in the line

I have a file name that can have several dots in it and can end with any extension:

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

I need to use a regular expression to replace the last occurrence of a point with another line, for example @2x , and then again with a period (very similar to the name of the retina image file), that is:

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

Here is what I have so far, but nothing will match ...

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

any suggestions?

+51
javascript jquery string regex
Jun 21 2018-12-12T00:
source share
9 answers

You do not need 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); } 

Look at the action .

Update: Regular solution, just for fun:

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

Corresponds to a literal point, and then claims ( (?=) positive result ) that no other character to the end of the line is a point. The replacement must include one point that has been matched if you do not want to delete it.

+92
Jun 21 '12 at 8:12
source share

Just use the special replacement pattern $1 in the replacement string:

 console.log("tro.lo.lo.lo.lo.lo.png".replace(/\.([^.]+)$/, "@2x.$1")); // "tro.lo.lo.lo.lo.lo@2x.png" 
+25
Jun 21. '12 at 8:16
source share

You can use the expression \.([^.]*?) :

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

You need to reference the subgroup $1 to copy the part back to the resulting row.

+6
Jun 21 '12 at 8:13
source share

working demo version http://jsfiddle.net/AbDyh/1/

the code

 var str = 'tro.lo.lo.lo.lo.lo.zip', replacement = '@2x.'; str = str.replace(/.([^.]*)$/, replacement + '$1'); $('.test').html(str); alert(str);​ 
+5
Jun 21 '12 at 8:15
source share

To combine all characters from the beginning of the line to (and including), the last use of the character is used:

 ^.*\.(?=[^.]*$) To match the last occurrence of the "." character ^.*_(?=[^.]*$) To match the last occurrence of the "_" character 
+3
15 Oct '13 at 21:07
source share

Use \. to match points. Symbol . matches any character.

Therefore str.replace(/\.([^\.]*)$/, ' @2x.') .

+2
Jun 21 '12 at 8:12
source share

You could just do it

 > "tro.lo.lo.lo.lo.lo.zip".replace(/^(.*)\./, "$1@2x"); 'tro.lo.lo.lo.lo.lo@2xzip' 
+1
Sep 21 '14 at 4:33
source share

Why not just break the line and add the specified suffix to the second-last entry:

 var arr = 'tro.lo.lo.lo.lo.lo.zip'.split('.'); arr[arr.length-2] += '@2x'; var newString = arr.join('.'); 
+1
Oct 22 '14 at 4:46
source share
 'tro.lo.lo.lo.lo.lo.png'.replace(/([^\.]+).+(\.[^.]+)/, "$1.@x2$2") 
+1
Dec 16 '15 at 17:14
source share



All Articles