Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split First name and Last name using JavaScript

I have a user with the name Paul Steve Panakkal. It's a long name it won't fit to the div container. So is there anyway to split first name and last name from it using JavaScript or jQuery?

The name is got from PHP into a variable in JavaScript. This is then splitted using JS.

like image 959
Subin Avatar asked Sep 09 '12 16:09

Subin


People also ask

How do you write first name and last name in JavaScript?

var fullName = "Paul Steve Panakkal". split(' '), firstName = fullName[0], lastName = fullName[fullName. length - 1];

How do you split items in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

What is a separator in JavaScript?

separator: It is optional parameter. It defines the character or the regular expression to use for breaking the string. If not used, the same string is returned (single item array). limit: It is optional parameter. It is an integer which specifies the number of splits.

Can we divide string in JavaScript?

You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.


1 Answers

You should use the String.prototype.split() method:

'Paul Steve Panakkal'.split(' '); // returns ["Paul", "Steve", "Panakkal"] 

You can use it this way:

'Paul Steve Panakkal'.split(' ').slice(0, -1).join(' '); // returns "Paul Steve" 'Paul Steve Panakkal'.split(' ').slice(-1).join(' '); // returns "Panakkal" 

So in common:

var firstName = fullName.split(' ').slice(0, -1).join(' '); var lastName = fullName.split(' ').slice(-1).join(' '); 
like image 90
Danil Speransky Avatar answered Sep 29 '22 14:09

Danil Speransky