Javascript separate string into different variables

后端 未结 5 1151
清歌不尽
清歌不尽 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:57

    I would create a function along these lines. This is just a quick-and-dirty and doesn't do any validation, I leave that up to you.

    function parse_name(theName) {
        var nameSplit = theName.split(" ");
    
        var nameFields = {
                first  : nameSplit[0],
                middle : nameSplit[1],
                last   : nameSplit[2]
            };
    
        return nameFields;
    }
    

    Then you can call it any time you need to parse a name.

    var parsedName = parse_name("John M Smith");
    
    alert(parsedName.first); // Should alert "John"
    alert(parsedName.middle); // Should alert "M"
    alert(parsedName.last); // Should alert "Smith"
    

提交回复
热议问题