This is already pretty simple. But I'd use the ternary operator ?:
to make it a bit more compact:
function validateDateFormat(format) {
return format.indexOf("yyyy") == -1 ? format : format.replace(/yy/g, 'y');
}
Also, perhaps you can be a bit more accurate.
There is a discrepancy between your check and the action taken:
- Check if string contains
"yyyy"
- Replace all occurrences of
"yy"
with "y"
Perhaps it would be more accurate to change the action to this:
Replace "yyyy"
with "yy"
(only once)
That is:
function validateDateFormat(format) {
return format.indexOf("yyyy") == -1 ? format : format.replace(/yyyy/, 'yy');
}
Actually, and probably I should have started with this:
since the .replace
method returns the original string if there is no match,
you could simplify even further:
function validateDateFormat(format) {
return format.replace(/yyyy/, 'yy');
}