2017-05-09 62 views
1

我已經使用stringreplace代碼如下所示。但它有一個問題。可否請告訴我爲什麼?字符串插值不工作

.TS

answerCode: string = 'answer_28903220'; 

constructor(){} 

let prompt = this.question.prompt.replace("{{this.answerCode}}", 
this.LookupAnswer(this.answerCode));//Not working: Output= "{{answer_28903220}} was born on:" 

let prompt = this.question.prompt.replace("{{answer_28903220}}", 
       this.LookupAnswer(this.answerCode));//This is working fine:output= Sampath was born on: 

LookupAnswer(answerCode: string): string { 
    let answer: string = ''; 
    _.some(this.answers, (value, key) => { 
     if (value.questionCode == answerCode.substring(7)) { 
     answer = value.answer; 
     return true; 
     } 
    }); 
    return answer; 
    } 
+0

'string Interpolate'與'typescript'有關嗎?它必須是一個「角」問題,對吧? @Andrew Shepherd – Sampath

+0

你的困惑以及後續的解決方案是模板文字。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals這是ECMA6 javascript的一部分,但也是打字稿中的一個功能。你特別告訴我們,代碼示例在打字稿中。 我不能在你的問題中看到任何角度相關的東西。 –

回答

5

按照文件上Template Literals,這種替換代碼:

let prompt = this.question.prompt.replace(`{{${this.answerCode}}}`,this.LookupAnswer(this.answerCode)); 

更換"與反引號`,並與封閉的可變${ }

+0

哦..非常好,謝謝你:) – Sampath

0

請嘗試使用字符串templ吃文字:

`${this.answerCode}`