0

I'm having problems to define a regex in javascript. I want to replace format strings in this format (i.e. "dd/mm/yy") by strings in this other format (i.e. "dd/MM/yyyy"). My problem is how to use javascript regex. For instance, how to convert the year? I've been trying to convert with these expressions:

f1 = "dd/mm/yy";
f1 = f1.replace(/[^y](yy)[^y]/g, 'yyyy');
f1 = f1.replace(/[^y](y)[^y]/g, 'yy');

With this I attempted to convert all 'yy' not sorrounded by any 'y' to 'yyyy' and then do the same with alone 'y', but I don't know how to say "yy not sorrounded by any y".

2 Answers 2

1

Group the character before y, and refer back to it using $1. "The character before" can be anything except for y. It's also allowed to have nothing before the y, hence |^.
Prefix your pattern by (?!y), which means "match if the next character does not equal y.

Adding both together:

f1 = "dd/mm/yy";
f1 = f1.replace(/([^y]|y)yy(?!y)/g, '$1yyyy');
f1 = f1.replace(/([^y]|^)y(?!y)/g, '$1yy');
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to match exactly two 'y's use /\by{2}\b/ \b is a word boundary which will include the start of the string, the end of the string, and your '/'s (etc.).

2 Comments

Exactly, Rob W has pointed a non matching regex using word boundaries.
The regex matches what's mentioned, dd/mm/yyo strikes me as very contrived as you'd end up with something like 01/01/111 which makes no sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.