2017-05-20 130 views
0

我正在嘗試查看JSON響應並每次在字符串(值)中出現「Sw」時都進行替換。舉例來說,利用這個JSON對象:替換字符串值中的值

[{"accountName":"MTVN\\lalalala", 
    "baseOfficeLocation":"657 Hudson Street Floor 11", 
    "department":"Mp - Engineering - Engineering", 
    "jobTitle":"Sw Test Engineer", 
    "preferredName":"Beddingfield,Natasha", 
    "workEmail":"[email protected]"}] 

我想更換,每次我拿到包括那些屠殺的話,如「MP」和「SW」和替換它們與它的整個單詞的響應。所以「Sw」會變成「軟件」。

下面是一些代碼,我到目前爲止,但我不認爲有經驗的在Node.js的好,所以想知道如何做到這一點(:

var baseOfficeLocation = jsonData.baseOfficeLocation; 
      console.log("Base Office Location: " + baseOfficeLocation); 
      var department = jsonData.department; 
      console.log("Department: " + department); 

      var workEmail = jsonData.workEmail; 
      console.log("Work Email: " + workEmail); 

      if (jsonData.jobTitle !== null) { 
       replaceString(jsonData.jobTitle, 'Sw', 'Software'); 
      } 
      console.log("Job Title: " + jobTitle); 

回答

0
var demo = [{"accountName":"MTVN\\lalalala", 
    "baseOfficeLocation":"657 Hudson Street Floor 11", 
    "department":"Mp - Engineering - Engineering", 
    "jobTitle":"Sw Test Engineer", 
    "preferredName":"Beddingfield,Natasha", 
    "workEmail":"[email protected]"}] 


console.log(replaceString(demo[0].jobTitle, 'Sw', 'Software')); // Software Test Engineer 

function replaceString(str, substr, newSubstr){ 
    var re = new RegExp(substr,"i"); 
    return str.replace(re, newSubstr); 
} 
+0

感謝這麼多,@NguyenTungs我怎麼會改變幾串後如出現在字符串響應。例如,讓我們在一個響應說,我們有「SFW」,這我想用sof代替tware,但在另一個迴應中,出現「Sw」。所以它能夠從字符串中提取很多選項,並用我們選擇的各種可能的替換字符串來改變它們。 – VeeArr

0

這裏是解決方案替換字符串:!

var demo = [{"accountName":"MTVN\\lalalala", 
    "baseOfficeLocation":"657 Hudson Street Floor 11", 
    "department":"Mp - Engineering - Engineering", 
    "jobTitle":"Sw Test Engineer", 
    "preferredName":"Beddingfield,Natasha", 
    "workEmail":"[email protected]"}] 
for(var key in demo[0]) { 
    demo[0][key] = demo[0][key].replace('Sw', 'Software'); 
}