Javascript separate string into different variables

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

    If you don't know how many spaces there are in the string, beforehand, you can do the following:

    var str = "How are you doing today, my dear friend?";
    numberspaces = str.split(" ").length; //you know how many spaces there are
    words=str.split(" ");                 //it creates an array of words
    var i;
    for (i = 0; i < numberspaces; i++){
    console.log(words[i]);}
    
    0 讨论(0)
  • 2020-12-11 13:42

    .split() just returns an array, so you can easily assign new variables using that...

    var str = "John M Peters";
    var fname = str.split(" ")[0];
    var mname = str.split(" ")[1];
    var lname = str.split(" ")[2];
    
    0 讨论(0)
  • 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/

    0 讨论(0)
  • 2020-12-11 13:54

    In addition to the answers the others pointed out, I'd like to point out that Mozilla's JavaScript engine (spidermonkey) supports destructuring assignments:

    <script language="javascript1.7">
      var s = 'John M. Peters';
      var fname, mname, lname;
    
      [fname, mname, lname] = s.split(/\s+/);
      alert('fname = ' + fname + ', mname = ' + mname + ', lname = ' + lname);
    </script>
    

    This is not portable, so not ideal for web programming. However, if you're writing a plugin for firefox or thunderbird or etc, then there are a number of interesting language extensions available.

    0 讨论(0)
  • 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"
    
    0 讨论(0)
提交回复
热议问题