Home > OS >  Regulare expression to remove everything after LAST match?
Regulare expression to remove everything after LAST match?

Time:04-27

I want to remove everything from a string after the last '.' For example:

aaa.bbb.ccc should become aaa.bbb and aaa.bbb.ccc.ddd should become aaa.bbb.ccc

What I currently have:

"([^[.*] )\."

But this removes everything after the first match, not the last. So it gives me:

aaa.bbb.ccc becomes aaa. and aaa.bbb.ccc.ddd becomes aaa.

CodePudding user response:

You could only match the non-periods. ie use:

\.[^.] $

This will only match the period and any non-period till the end.

Note that depending on the regex tool, and if your tool supports look-ahead, you could consider capturing everything before the last period. ie:

 (. )\.(?=[^.] $)

CodePudding user response:

try "aaa.bbb.ccc".replace(/\..*/, '') or split it with with ( . ) "aaa.bbb.ccc".split('.')[0]

CodePudding user response:

You may try this:

let str = "aaa.bbb.ccc.ddd";
let strArr = str.split(".");
strArr.pop();
strArr.join('.')
  • Related