Javascript从字符串中提取值 - 股票和公司名称

时间:2017-01-03 08:12:07

标签: javascript regex string

我有两个字符串,我想从中提取特定的字符串。

var companyString1;
var companyName1;

var companyString2;
var companyName2;

var stockString1 = "STOCKDETAILS:TWEETS:FB:Facebook Inc.";

var stockString2 = "I have returned -- Facebook Inc. (FB) -- stock back.";

companySymbol1 = ? //would like this to be "FB"
companyName1 = ? //would like this to be "Facebook Inc."
companySymbol2 = ? //would like this to be "FB"
companyName2 = ? //would like this to be "Facebook Inc."

什么是正则表达式我可以应用于stockSTring1来提取" FB" (进入companySymbol1 var)和" Facebook Inc。" (进入companyName1 var)。同样,我想提取" FB" (进入companySymbol2 var)和" Facebook Inc。" (来自companyName2 var)来自stockString2。

stockString1,stockString2的格式将保证来源一致 - 所以你可以假设可能有其他符号和名称(例如GOOG / Google Inc,MSFT / Microsoft Corp.等)

真的很感激任何帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用split和一个正则表达式执行此操作,以便在第二种情况下切断结束)



function getStock(s) {
    var parts = s.split(/\)? -- /);
    if (parts.length < 2) { // other format
        return s.split(':').slice(2, 4);
    }
    return parts[1].split(' (').reverse();
}

var stockString1 = "STOCKDETAILS:TWEETS:FB:Facebook Inc.";
var stockString2 = "I have returned -- Facebook Inc. (FB) -- stock back.";

var [companySymbol1, companyName1] = getStock(stockString1);
var [companySymbol2, companyName2] = getStock(stockString2);

console.log(companySymbol1, companyName1);
console.log(companySymbol2, companyName2);
&#13;
&#13;
&#13;