Home > front end >  Some regular expressions I've been studying
Some regular expressions I've been studying

Time:03-09

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".

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?

CodePudding user response:

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(/\..*/, ''));

CodePudding user response:

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

Yep, that's the start of the string, but if you're wanting all of the string it has no relevance. Also, go enter image description here

  • Related