2014-01-18 34 views
0

我想轉換字符串以使用變量和參數來構建它。通過調用自定義函數來將var轉換爲子字符串來替換字符串 - Algo JS

The min length of __40 is 4. Max length is 16. 

__40是另一串鑰匙,我需要提取從串鑰匙,將其轉換並與轉換後的值來替換它(這將是由密鑰字符串引用),要做到這一點,我需要調用一個自定義函數[_getSentence()],可能在同一個句子中有幾個鍵,我想要做一個正則表達式,但看起來很複雜,不是嗎?另外我不知道我是否可以從正則表達式調用一個自定義的函數,但我不這麼認爲。

可能會拆分字符串以獲取所有單詞(按空格拆分),每次檢查單詞是否以'__'開頭,在這種情況下調用我的自定義函數,存儲結果並用字符串替換當前單詞。但是這個新字符串還可能包含我需要轉換的另一個鍵。

什麼是最好的算法在這裏使用?你有沒有更好的解決方案?我應該工作。

我也必須處理可以發送的參數,但我不必管理子鍵的參數。

下面是函數,一旦句子被轉換後由_getSentence()調用,以用值替換args,但我還認爲在這裏管理子鍵。

/** 
* Replace the tags in the text by the args. 
* @param message  The message. 
* @param args   The args to replace in the message. 
* @returns {string} The string built. 
*/ 
Lang.prototype._replaceArgsInText = function (message, args, lang) { 
     for (var i = 0; i < args.length; i++) { 
      message = message.replace((this.PATTERN_ARGS + i), args[i]); 
     } 

     // Check if some of the args was other language keys. 
     return message; 
    }; 

編輯: 最終的解決方案:

/** 
* Replace the tags in the text by the args. 
* @param message  The message. 
* @param args   The args to replace in the message. 
* @returns {string} The string built. 
* @private 
*/ 
private _replaceArgsInText(message: any, args: any, lang: string): string{ 
    for(var i = 0; i < args.length; i++){ 
     message = message.replace((this.PATTERN_ARGS+i), args[i]); 
    } 

    // Check if some of the args was other language keys. 
    message = this._replaceSubKeys(message, /__\w+/g, this._languages[lang][this._FIELD_CONTENT_LANG]); 

    return message; 
} 

/** 
* Replace the sub keys into the sentence by the actual text. 
* @param sentence 
* @param rx 
* @param array 
* @returns {string|void} 
* @private 
*/ 
private _replaceSubKeys(sentence, rx, array): string{ 

    return sentence.replace(rx, function(i) { 
     var subSentence = array[i]; 
     // TODO Check if that's an object or a string. 
     if(typeof subSentence == 'string'){ 
      return subSentence; 
     }else{ 
      console.log('not a string!') 
      return null; 
     } 
    }); 
} 
+0

你問什麼語言?您的文章標記爲'javascript',但您的示例代碼不是'javascript'。 – jfriend00

+1

TypeScript可能? – elclanrs

+0

其實是的,它是typescrit,所以它就像javascript,但源代碼是面向對象的。 – Vadorequest

回答

1

假設你有與他們作爲鍵名稱的地圖的替代參數,你可以做這樣的事情:

function replace(text, rx, map) { 
    return text.replace(rx, function(k) { return map[k] }); 
} 

var res = replace(
    "The min length of __40 is 4. Max length is 16.", 
    /__\w+/g, // regex for the substitution format 
    {__40: 'snake'}); // map of substitution parameters 

正則表達式是/__w+/g以匹配參數的格式以及字符串中的所有參數。小提琴here

我也在使用String.prototype.replace function,它也是一個函數。

+0

謝謝,這是行之有效的! – Vadorequest

+0

@Vadorequest:不客氣! –