-1

For example, I have a string "esolri.gbn43sh.earbnf", and I want to remove every character after the last dot(i.e. "esolri.gbn43sh"). How can I do so with regular expression?

I could of course use non-RegExp way to do it, for example:

"esolri.gbn43sh.earbnf".slice("esolri.gbn43sh.earbnf".lastIndexOf(".")+1);

But I want a regular expression.

I tried /\..*?/, but that remove the first dot instead.

I am using Javascript. Any help is much appreciated.

  • Possible duplicate of [Learning Regular Expressions](http://stackoverflow.com/questions/4736/learning-regular-expressions) – Biffen Oct 16 '16 at 11:21

2 Answers2

1

Pattern Matching

Match a dot followed by non-dots until the end of string

let re = /\.[^.]*$/;

Use this with String.prototype.replace to achieve the desired output

'foo.bar.baz'.replace(re, ''); // 'foo.bar'

Other choices

You may find it is more efficient to do a simple substring search for the last . and then use a string slicing method on this index.

let str = 'foo.bar.baz',
    i = str.lastIndexOf('.');

if (i !== -1) // i = -1 means no match
    str = str.slice(0, i); // "foo.bar"
Paul S.
  • 64,864
  • 9
  • 122
  • 138
1

I would use standard js rather than regex for this one, as it will be easier for others to understand your code

var str = 'esolri.gbn43sh.earbnf'
console.log(
  str.slice(str.lastIndexOf('.') + 1)
)
synthet1c
  • 6,152
  • 2
  • 24
  • 39