首页 > 解决方案 > Javascript在Excel中将两列名称合并为一列

问题描述

我正在使用 Data Miner 从网站表中抓取名称列表。我正在尝试将名称添加到 Excel 列中。被抓取的名称采用姓氏,名字格式。以下是一些供参考的名称。我想重新排列名称,使名字排在姓氏之前并删除逗号。我已经能够拆分名称,使用下面的代码在第 1 列中添加名字,在第 2 列中添加姓氏。我无法将名称带回第一列。如果有人能告诉我如何做到这一点,那就太好了。此外,Ted Potter Jr. 先生的名字中有 2 个逗号。我能做些什么来确保格式与其余名称匹配,但在 Potter 和 Jr. 之间留下逗号?

标签: javascriptexcel

解决方案


如果没有上下文/更多代码,这有点难以判断,但总的来说,我认为这样的事情会起作用。

如果您想要一个真实的示例,请参见此处:https ://jsfiddle.net/pqjd2h5a/

  • 做你的分裂
  • 将数组的最后一个元素放在前面/到第 1 列
  • 循环遍历剩余元素并将它们在第 2 列连接在一起
  • 在第 3 列中将名字和姓氏连接在一起

也许是这样的:

var cleanup = function(results) {

$.each(results, function(){
    //split the string of "Baker, Chris" into an array of ["Baker", "Chris"]
    //split the string of "Potter, Jr., Ted" into an array of ["Potter", "Jr.", "Ted"]
    var parts = this.values[0].split(', ');

    //set the first column to the last element of the array. i.e. "Chris" or "Ted"
    //this.values[0] = parts[parts.length - 1];
    var first_name = parts[parts.length - 1];

    //Loop through the remaining elements
    //for "Baker, Chris" this will just be one loop
    var second_name = "";
    for (var i = 0; i < parts.length - 1; i++) {
        //if i = 0 then just add the element otherwise
        //if i > 0 then add what is already there plus space plus next element
        if (i > 0) {
            //this.values[1] = this.values[1] + " " + parts[i];
            second_name  = second_name + " " + parts[i];
        }else {
            //this.values[1] = parts[i];
            second_name = parts[i];
        }
    }
    //concatenate the results together in the third column
    //i.e. "Chris Baker" or "Ted Potter Jr."
    //this.values[2] = this.values[0] + " " + this.values[1];

    //Or now output only in first column
    this.values[0] = first_name + " " + second_name;
});

return results;};

推荐阅读