如何从String中提取关键字并将其放入对象或数组中?

时间:2019-04-09 16:40:00

标签: javascript string

我是一个字符串,要从字符串中获取2个关键字,但要在数组或对象中使用。

字符串看起来像这样

”方案:“付款类型”:“任何”,“客户类型”:“任何”,国际市场卡成员验证“左导航”元素,因为我是“付款类型”:“任何”,“客户类型” :“国际市场卡会员”“任何”,当我导航到“帐户管理”视图时,我应该看到卡管理链接,并且应该看到“个人资料”链接,并且应该看到“警报和通讯”链接。

function takeKeyWord(str) {

  String(str)
  let arr = str.split(/[,:]+/)
  let sol = []

  for (let i = 0; i < arr.length; i++) {
    console.log(i)
    console.log(arr[i])
    if (arr[i].includes('Payment Type') || arr[i].includes('Customer Type')) {
      arr[i].replace(/'/g, "@@@");
      sol.push(arr[i + 1])

    }
  }

  console.log('sol', sol)
  return sol
}

我希望输出应该是这样

obj = {
  PaymentType:"Any",
  Customer:"Any"
}

1 个答案:

答案 0 :(得分:0)

使用对象会更容易。如果无法将数据作为对象获取,则下面的代码可让您在将字符串分割为数组后从字符串中提取所需的内容。

let mystr ="Scenario: A 'Payment Type': 'Any', 'Customer Type': 'Any', International market card member validates Left Nav elements Given I am a 'Payment Type': 'Any', 'Customer Type': 'Any', International market card member When I navigate to the Account Management view Then I should see the Card Manage link And I should see the Profile link And I should see the Alerts & Communications link";


const extract = (str) => {
  // Split the string and filter non whitespaces
  let arr = str.split(/[,:']+/).filter(item => item != ' ');

  let obj = {};
  // Loop, look for the keys and put them in an object
  arr.map(function(item, index) {
    if(item.includes('Payment Type')) obj['PaymentType'] = arr[arr.indexOf(item)+1];
    else if(item.includes('Customer Type')) obj['Customer'] = arr[arr.indexOf(item)+1];
  });
  return obj;
}
console.log(extract(mystr));