Split First name and Last name using javascript

后端 未结 20 3174
悲&欢浪女
悲&欢浪女 2020-12-08 06:39

I have a user with a 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 lastname fro

20条回答
  •  情歌与酒
    2020-12-08 07:02

    Use this code:

    You'll need to change the line: splitFullName("firstName","lastName","fullName"); and make sure it includes the right field IDs from your form.


    function splitFullName(a,b,c){
        String.prototype.capitalize = function(){
            return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
        };
        document.getElementById(c).oninput=function(){
            fullName = document.getElementById(c).value;
            if((fullName.match(/ /g) || []).length ===0 || fullName.substring(fullName.indexOf(" ")+1,fullName.length) === ""){
                first = fullName.capitalize();;
                last = "null";
            }else if(fullName.substring(0,fullName.indexOf(" ")).indexOf(".")>-1){
                first = fullName.substring(0,fullName.indexOf(" ")).capitalize() + " " + fullName.substring(fullName.indexOf(" ")+1,fullName.length).substring(0,fullName.substring(fullName.indexOf(" ")+1,fullName.length).indexOf(" ")).capitalize();
                last = fullName.substring(first.length +1,fullName.length).capitalize();
            }else{
                first = fullName.substring(0,fullName.indexOf(" ")).capitalize();
                last = fullName.substring(fullName.indexOf(" ")+1,fullName.length).capitalize();
            }
            document.getElementById(a).value = first;
            document.getElementById(b).value = last;
        };
        //Initial Values
        if(document.getElementById(c).value.length === 0){
            first = document.getElementById(a).value.capitalize();
            last = document.getElementById(b).value.capitalize();
            fullName =  first + " " + last ;
            console.log(fullName);
            document.getElementById(c).value = fullName;
        }
    }
    
    //Replace the ID's below with your form's field ID's
    splitFullName("firstName","lastName","fullName");
    

    Source: http://developers.marketo.com/blog/add-a-full-name-field-to-a-marketo-form/

提交回复
热议问题