如何从字符串中取出一个子字符串并将另一个字符串附加到该字符串并将其转换为数组

How to take a substring from a string and attach another string to the string and convert it to an array

我在一个数组中有一些字符串,其形式为 Exit Survey [hr.exitinterview], Certificate [hr.certificate], Recommendation Letter [hr.recommendation] 我只需要从现有字符串中提取 hr.exitinterview, hr.certificate, hr.recommendation 并向每个子字符串添加另一个字符串 https://somelink/hr.exitinterview, https://somelink/hr.certificate, https://somelink/hr.recommendation 和return 将它们作为数组传递给另一个函数。我试过尝试使用子字符串并将新字符串添加到数组中,但它只显示 ,,,,,。请问是什么原因还是代码有什么问题,我还在学习JS,如果是愚蠢的问题请忽略。

var sheet = SpreadsheetApp.getActive().getSheetByName("Form Responses 2");
var data = sheet.getDataRange().getValues();
var currentTime = new Date();
Logger.log('currentTime:'+ currentTime);
for (var i = 1; i < data.length; i++) {
    var checkbox = data[i][7];
    var links = extract(checkbox);
    Logger.log('New links: ' + links);
  }
}

function extract(data) {
  var lengthOfData = [ data.length];
  if (lengthOfData > 0) {
      var extractedLinks = extractLinks(data);
  }
  if (extractedLinks.length > 0) {
    return extractedLinks;
  }
  else
  {
    return -1;
  }
  return -1;
}

function extractLinks(link) {
  var extractedLinks = [];
  for (var i = 0; i < link.length; i++) {
    link[i] = JSON.stringify(link[i]);
    extractedLinks.push(link[i].substring(link[i].lastIndexOf("["),link[i].lastIndexOf("]")));
    extractedLinks.map(function(a) { return "https://somelink/" + a; }).join("");
  }
  return (extractedLinks);
}

使用正则表达式提取方括号之间的值,然后mapjoin他们:

const inputs = [
'Exit Survey [hr.exitinterview], Certificate [hr.certificate], Recommendation Letter [hr.recommendation]',
'Exit Survey [aaa], Certificate [bbb], Recommendation Letter [ccc]',
'Exit Survey [qqqqq], Certificate [qwert], Recommendation Letter [12345]',
];
const outputs = inputs.map((input) => {
  const strings = input.match(/[^\[\]]+(?=\])/g);
  const newFullStr = strings
    .map(str => 'https://somelink/' + str)
    .join(', ');
  return newFullStr;
});
console.log(outputs);

在大多数情况下,数组方法远远优于 for 循环。