简体   繁体   中英

Splitting a string into 3 substrings jquery/javascript

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!

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 ;)

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/

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()" />

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.

Here is an approach

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

Then usually,

  1. 0 th 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM