Get first and last name of a string

5

I need to get the first and last name of a string. For example, if the full name is:

Renan Rodrigues Moraes

I only need to get Renan Rodrigues . I know what I should do but I do not know how. In case the name is Renan de Assis it would be interesting to return Renan de Assis .

I know what I should do, but I do not know how.

The main idea is to count two spaces, from the second show nothing. Does anyone have a suggestion to extract this from the string?

    
asked by anonymous 27.04.2016 / 15:29

4 answers

10

You can use .split(' ') to create an array. Then using .slice(0, 2) create a copy with only the first two. Finally, if you want to return a string, you can do .join(' ') :

'Renan Rodrigues Moraes'.split(' ').slice(0, 2).join(' ');

example: link

If there are names with de or do such as Renan de Assis you could use regex like this ( link ) , or check if the second word begins with large print like this ( link ), like this:

function nome(str) {
    var arr = str.split(' ');
    if (arr[1][0].toUpperCase() != arr[1][0]) arr.splice(1, 1);
    return arr.slice(0, 2).join(' ');
}

In any case, you need to create some examples and test to make sure it works the way you want ...

And to keep these de / do you could do this:

function nome(str) {
    var arr = str.split(' ');
    var keep = arr[1][0].toUpperCase() != arr[1][0];
    return arr.slice(0, keep ? 3 : 2).join(' ');
}

jsFiddle: link

    
27.04.2016 / 15:38
3

You can split the white space in the string, then take only the first and second elements of the array:

var nome = "Renan Rodrigues Moraes";
var tmp = nome.split(" ");
nome = tmp[0] + " " + tmp[1];

Edit:

However, you will need a special treatment for cases where the name is "João da Silva", because in this case it would be "João da".

    
27.04.2016 / 15:40
2

You can use JS Split to get the String name and surname from their spaces.

It would look like this:

var nomeCompleto = "Renan Rodrigues Moraes";
var nome = nomeCompleto.split(" ")[0];
var sobrenome = nomeCompleto.split(" ")[1];
    
27.04.2016 / 15:39
2

Considering my comment in Sérgio's answer ...

The problem is to ensure that in the register the, from or are not written in capital letters. I thought about considering the number of characters but would give problems in names like Antônio de Sá. Perhaps your function can really ignore the conditions of, of, and of being already unique, I believe.

Here's a possible solution:

function nome(str) {
    var arr = str.split(' ');
    if(arr[1].toLowerCase() == 'de' || arr[1].toLowerCase() == 'da' || arr[1].toLowerCase() == 'do') {
        return arr[0] + " " + arr[1] + " " + arr[2]
    } else {
        return arr[0] + " " + arr[1]
    }
}

console.log(nome('Renan de Rodrigues Moraes'));
console.log(nome('Renan DE Rodrigues Moraes'));
console.log(nome('Antônio De Sá Moreira'));
    
27.04.2016 / 22:49