Format string for (dd/mm)

Asked

Viewed 57 times

3

I get a 4-digit string (numbers), and I need to break it in half, and put a "/", to format in type (dd/mm)

<input [(ngModel)]="contato.birth" class="form-control" type="text" placeholder="DIA/MÊS" mask="99/99" />

and when displaying this value, I need it to be formatted in Javascript, such as (dd / mm) as "06/08", for example. I tried to use the split and Join functions, but I didn’t have much success, I tried it:

formatBirthday(date) {
    let result = date.split('-').join('/');

    return result
}
<p *ngIf="business.cliente.birth">
  <b class="b-b">Aniversário: </b>
  {{formatBirthday(business.cliente.birth)}}
</p>

someone would know some way to format only dd / mm?

  • Your question is not clear!

  • I edited the question, I think it improved

2 answers

2

You can use the method Slice() to do this in a very simple way, remembering that this can be done in various ways, such as the use of a regex for example:

let date = '0608';

console.log(`${date.slice(0,2)}/${date.slice(2,4)}`)

  • That way also solved the problem, thank you ;) !!!

2


It is also possible to use regular expressions to do this. See:

/^(\d{2})(\d{2})$/

In the above expression, we create two capture groups. Each one of them will search by double-digit sequence. For this, we use the shortcut to the character class number ([0-9]) \d next to the quantifier {2}.

So you can do it like this:

const re = /^(\d{2})(\d{2})$/;
const str = '0608';

const [, day, month] = str.match(re);

const dateStr = `${day}/${month}`;

console.log(dateStr);

The method match was used. It will return a array with the catch groups found from index 1. Thus, we use the disruption of arrays to obtain them.

  • Great answer, helped me with the problem, thank you ;) !!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.