How to display only the first user name in EJS

Asked

Viewed 64 times

1

I’m blogging to train with Ode. In the application, the user registers in the database and, after logging in, goes to his page, where are all his articles. The field in SQL goes as name, and I re-address passing to the EJS through a variable user.name.

<h2>Olá, <span id="trocarNome"><%-user.name%></span></h2>

This code is coming out like this:

Hello, Gustavo Henrique

I wish only the first name came out:

Hello, Gustavo

I would like to make Javascript use the function .split(' '), doing so he brings me the name to the first space. But how do I put it into practice?

  • Have you ever tried something like const primeiroNome = user.name.split(' ')[0]; and put this primeiroNome in the EJS?

  • 1

    worked out, thanks!!

1 answer

3

As indicated in the comment, here is a possible solution to the problem:

We use the function split() to obtain an "array of names" from user.name and select the first of the "names" of that array with [0]

const primeiroNome = user.name.split(' ')[0];

And then, at EJS, we make that first name appear that way:

<h2>Olá, <span id="trocarNome"><%-primeiroNome%></span></h2>

Browser other questions tagged

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