Javascript separate string into different variables

后端 未结 5 1171
清歌不尽
清歌不尽 2020-12-11 13:12

I am looking to take a string and find all the spaces in it and separate that into different variables. I know I could use the .split() but that wouldn\'t make

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 13:53

    You can split the string like so:

    var name = 'John M Peters';
    var arr = name.split(' ');
    
    var obj = {fname: arr[0]};
    if(arr.length === 1) {
        obj.lname = arr[1];
    } else {
        obj.mname = arr[1];
        obj.lname = arr[2];
    }
    
    console.log(obj.fname);
    console.log(obj.mname); //could be undefined
    console.log(obj.lname);
    

    This solution will also work for a string that does not have a middle initial as well. You can see this example here: http://jsfiddle.net/nDwmY/2/

提交回复
热议问题