Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Some regular expressions I've been studying

I’ve found these regex elsewhere:

myString.replace(/^.*\//, '');
myString.replace(/\..*?$/, '');

My question is:

  • do ^ and ?$ make any sense here?

And my interpretation is that ^ isn’t relevant, because we are using .* which means "anything".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The second one means replace from the . any character in lazy mode till the end of the string. Which is the same as nothing.

So I’d write them:

myString.replace(/.*\//, '');
myString.replace(/\..*/, '');

But I am not 100% sure as my Regex is quite basic. Ideas?

>Solution :

Indeed, in the first regular expression the ^ is not really needed. The effect is the same without it.

However, in the second regular expression there is a difference when you omit the ? and the $, because . does not match newline characters (unless you add s as modifier).

See the different results:

let myString = `.this
is multiline`;


console.log(myString.replace(/\..*?$/, ''));

console.log(myString.replace(/\..*/, ''));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading