2017-01-02 48 views
-1

我有一個大的文本字段存儲在數據庫中。文本字段在特定位置播種變量,類似於console.log()的工作方式。Javascript - 將字符串插入可變位置的文本

「這段文字被寫了$ USER1,在$日期,而$ USER1與$ user2的工作完成$主題」

然後,我可以換出用正確的動態值的變量。

好奇的是,如果有一個簡單的方法來解決這個問題,或者我堅持在每個位置分割字符串,然後用新值重建。

+0

您的變量是如何模樣?提供您使用的完整字符串/變量/數據。 – Dekel

回答

0

你可以在javascript中使用replace函數,它使用正則表達式。

實施例:

var user1 = "Joe"; 
var original = "This text was written by $user1, on $date, while $user1 was working with $user2 to complete the $subject"; 
var newString = original.replace(/\$user1/g, user1); 

等。

+0

完美,謝謝塔爾。 – opusprime

+0

不客氣:)如果有幫助請標記爲答案 –

0

String.prototype.replace可以調用RegExp進行匹配和一個函數來動態確定替換字符串。如果您可以創建一個具有與格式字符串中的變量相同屬性名稱的對象映射,並使用替換本身創建值,則可以使用匹配的屬性名稱將其全部替換爲從映射對象獲取相應值。

事情是這樣的:

var format = "This text was written by $user1, on $date, while $user1 was working with $user2 to complete the $subject"; 
 

 
var replacementsMap = { 
 
    user1: "John", 
 
    date: new Date(), 
 
    user2: "Jane", 
 
    subject: "Collaboration Project" 
 
}; 
 

 
var result = format.replace(/\$([a-z]+\d*)/g, function(match, prop) { 
 
    // match => the full string matched by the regex (e.g. $user1, etc) 
 
    // prop => the captured part of the match (i.e. not including the $) 
 
    return replacementsMap[prop]; 
 
}); 
 

 
document.getElementById("result").innerHTML = result;
<div id="result"></div>

+0

天才!謝謝Brian – opusprime

+0

不客氣,@opusprime。 :) – Bryan

相關問題