1

I have a text field in which I write the full name of the employee. I want to retrieve the first word as first name, last word as last name and the remaining middle string as middle name. For eg. for

ramesh suresh mahesh roshan

the first name should be ramesh, middle name as suresh mahesh and last name as roshan.

Is there any way to do this using jquery/javascript? Please help!

Strife
  • 243
  • 7
  • 22
  • what is the rule to split – Arun P Johny Jan 10 '14 at 04:40
  • Suppose u store ur database value in a var x(array),u can split with `var x=x.split(" ");var a=x1[0]; var b=x[1];var c=x[2];var d=x[3];` so a=ramesh,b=suresh...d=roshan – Santino 'Sonny' Corleone Jan 10 '14 at 04:41
  • 1
    from what I can see something like `'ramesh suresh mahesh roshan'.match(/(.*?)\s(.*)\s(.*)/)` – Arun P Johny Jan 10 '14 at 04:42
  • possible duplicate of [How do I split this string with JavaScript?](http://stackoverflow.com/questions/96428/how-do-i-split-this-string-with-javascript) – Sean Vieira Jan 10 '14 at 04:43
  • @ArunPJohny can you show me jsfiddle for the same. I am really confused. – Strife Jan 10 '14 at 04:45
  • his comment returns an array whose first element is the entire match and the remaining elements, ie. [1] [2] [3] are the captured groups, ie. first name, middle name, last name. you can store the result in the variable like so: `var namearray = somestringvariable.match(/(.*?)\s(.*)\s(.*)/)` and access the names like so: `namearray[1]` would retrieve the first name. if you have a user input or html element you can use something like: `$('input').val().match(/(.*?)\s(.*)\s(.*)/)` or `$('div').text().match(/(.*?)\s(.*)\s(.*)/)` – tenub Jan 10 '14 at 04:48
  • @ArunPJohny your regex fails with "John Smith" xD – Edgar Villegas Alvarado Jan 10 '14 at 05:23

5 Answers5

4

With this:

var fullName = "ramesh suresh mahesh roshan",
    parts = fullName.split(/\s+/),  //Divide by one or more spaces
    firstName = parts.shift(),     //Extract first word
    lastName = parts.pop() || '',         //Extract last word
    middleName = parts.join(' ');   //All the rest

EDIT: added || '' fallback for lastName in case full name has only 1 word (well, mainly for the paranoic reviewers xD)

Cheers ;)

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
  • *just to let you know* that you need to include a conditional statement to last name otherwise it will fail for "ramesh" http://jsfiddle.net/fFPkx/5/ – Praveen Jan 10 '14 at 05:39
1

Below code will help you

var temp = 'ramesh suresh mahesh roshan';
var fullname = temp.split(" ");
var firsname='';
var middlename='';
var lastname = '';
firstname=fullname[0];
lastname=fullname[fullname.length-1];
for(var i=1; i < fullname.length-1; i++) {
   middlename =  middlename +" "+ fullname[i];
}
alert(firstname);
alert(middlename);
alert(lastname);

http://jsfiddle.net/c9h74/

frangly
  • 162
  • 7
0

This may do the trick

 <script>
        function getnam(){                
            var val = $("#txtval").val();               
            var dssr = val.split(" ");
            var len = dssr.length;                
            alert("First Name:" + dssr[0]);               
            var mn = "";
            if(len>2){
                for(var i=1;i<len-1;i++){
                    mn= mn + " " + dssr[i];
                }
            }
            alert("Middle Name:" + mn);
            if(len>1){
                alert("Last Name:" + dssr[len-1]);
            }
        }
    </script>


    <input type="text" id="txtval"/>
    <input type="button" onclick="getnam()" />
Myth
  • 446
  • 7
  • 18
0

Here is an approach

  1. Split the string based on space using string.split(" ").

Then usually,

  1. 0th index - represents first name
  2. (last - 1)th index - represents the last name
  3. So for middle name I'm iterating the remaining index and concatenating each other.

var name = "ramesh suresh mahesh roshan";
var d = name.split(" ")

console.log("first Name : " + d[0]);
console.log("Last Name : " + d.length != 1 ? d[d.length -1] : "");
var mid = "";
for (var i = 1; i <= d.length - 2; i++) {
    mid = mid + " " +  d[i];
}
console.log("middle name: " +mid);

JSFiddle

Praveen
  • 55,303
  • 33
  • 133
  • 164
  • 1
    This is a bit fragile because it will break if there is only a first and last name, or even just a first name. – Peter Jan 10 '14 at 05:16
  • 1
    @Peter In my form its compulsory to write the first name and last name. So it works for me. – Strife Jan 10 '14 at 05:27
  • @DarkKnight Even so, unless you handle these cases you open up the opportunity for nasty bugs—for example, this allows a case where the user can enter just a first name, and now you have `"ramesh ramesh"` in your system. – Peter Jan 10 '14 at 06:13
  • @Peter for your [comment](http://stackoverflow.com/questions/21036322/splitting-a-string-into-3-substrings-jquery-javascript/21036446?noredirect=1#comment31626622_21036621) no, check this http://jsfiddle.net/fFPkx/3/ – Praveen Jan 10 '14 at 06:15
0

JavaScript String split() function

The split() method is used to split a string into an array of substrings, and returns the new array.

var str = "ramesh suresh mahesh roshan";
var res = str.split(" ");

The result of res will be an array with the values:

ramesh,suresh,mahesh,roshan

Definition: The split() method is used to split a string into an array of substrings, and returns the new array.

Tip: If an empty string ("") is used as the separator, the string is split between each character.

Note: The split() method does not change the original string.

Syntax:string.split(separator,limit)

Parameter Values :

  • separator - Optional. Specifies the character, or the regular expression, to use for splitting the string. If omitted, the entire string will be returned (an array with only one item).
  • limit- Optional. An integer that specifies the number of splits, items after the split limit will not be included in the array.

Answer to your question:

As many folks already given so many correct answer still I wanted to give some light from my end.

JavaScript Based Answer

function fnStringSplitter(fullName,separator){
var mName = ""; //Middle Name
var splittedArr = fullName.split(separator);
for (var i = 1; i <= splittedArr.length - 2; i++) {
    mName = mName + " " +  splittedArr[i];
}
alert("First Name : " + splittedArr[0]);
alert("Middle Name : " + mName);
alert("Last Name : " + splittedArr[splittedArr.length - 1]);

}

Calling to function: fnStringSplitter("ramesh suresh mahesh roshan"," ");

Output: 3 alerts with first,middle and last name.

SK.
  • 4,174
  • 4
  • 30
  • 48