2017-01-02 47 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

相关问题